3 回答

TA貢獻(xiàn)2021條經(jīng)驗 獲得超8個贊
執(zhí)行此操作的方法家族是:
int indexOf(String str)
indexOf(String str, int fromIndex)
int lastIndexOf(String str)
lastIndexOf(String str, int fromIndex)
返回指定子字符串的第一個(或最后一個)出現(xiàn)在此字符串內(nèi)的索引[ 從指定索引處開始向前(或向后搜索)]。
String text = "0123hello9012hello8901hello7890";
String word = "hello";
System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"
// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
System.out.println(i);
} // prints "4", "13", "22"
// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
System.out.println(i);
} // prints "22", "13", "4"

TA貢獻(xiàn)1836條經(jīng)驗 獲得超5個贊
這使用正則表達(dá)式工作。
String text = "I love you so much";
String wordToFind = "love";
Pattern word = Pattern.compile(wordToFind);
Matcher match = word.matcher(text);
while (match.find()) {
System.out.println("Found love at index "+ match.start() +" - "+ (match.end()-1));
}
輸出:
在索引2-5中找到“愛”
一般規(guī)則 :
正則表達(dá)式從左到右搜索,并且一旦使用了匹配字符,便無法重復(fù)使用。

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
查找單個索引
正如其他人所說,用于text.indexOf(match)查找單個匹配項。
String text = "0123456789hello0123456789";
String match = "hello";
int position = text.indexOf(match); // position = 10
查找多個索引
由于@StephenC對代碼可維護性的評論以及我自己在理解@polygenelubricants的答案方面的困難,我想找到另一種方法來獲取文本字符串中匹配項的所有索引。以下代碼(通過此答案進(jìn)行了修改)做到了:
String text = "0123hello9012hello8901hello7890";
String match = "hello";
int index = text.indexOf(match);
int matchLength = match.length();
while (index >= 0) { // indexOf returns -1 if no match found
System.out.println(index);
index = text.indexOf(match, index + matchLength);
}
添加回答
舉報