定位单词一部分的方法

Method of locating a part of a word

我对 Java 编程还很陌生,我想知道是否有任何方法可以在句子的最后一个单词中定位一组特定的字符。

这方面的一个例子是尝试在短语中找到字符 "go":我要去 Go-station。

看看这个,我们可以看到字符 "go" 出现了两次,但是有什么方法可以只在短语的最后一个单词中定位 "go" ("Go-station")而不是第一个。

编辑:这个方法 lastIndexOf(String str) 巧合地工作。 @Zar 的回答是正确的。让我在这里写下我自己的更正版本,因为这个答案已经被接受。

String[] words = "I'm am going to the Go-station.".split(" ");
int index = words[words.length - 1].toLowerCase().indexOf("go");

if (index == -1) {
System.out.println("Not found");
} else {
int result = "I'm am going to the Go-station.".length() - words[words.length - 1].length() + index;
System.out.println("found it at postion: " + result);
}

我认为这可行:

String phrase = "I'm am going to the Go-station.";
String[] words = phrase.split(" ");
int relIndex = words[words.length - 1].toLowerCase().indexOf("go");

if (relIndex == -1) {
    System.out.println("Not found");
} else {
    int index = phrase.length() - words[words.length - 1].length() + relIndex;
    System.out.println("Index: " + index);
}

很容易理解,但可能还有更简单的方法。

我将短语分解成单独的词,然后检查最后一个词的索引 "go"。然后使用短语最后一个词中 "go" 的相对索引,我计算出原始短语中 "go" 的索引。