2013-02-26 71 views
3

我用這個來源:如何查找字符串中的所有第一個索引?

String fulltext = "I would like to create a book reader have create, create "; 

String subtext = "create"; 
int i = fulltext.indexOf(subtext); 

但我發現只有第一個指標,如何找到字符串中的所有一級指標? (在這種情況下爲三個指數)

回答

7

你已經找到了第一個索引後,使用的indexOf接收開始索引作爲第二個參數的重載版本:

public int indexOf(int ch, int fromIndex)返回此字符串內的索引第一次出現指定的字符,開始在指定的索引處進行搜索。

繼續做下去,直到indexOf返回-1,表示沒有更多匹配被發現。

0

您想創建一個while循環並使用indexof(String str, int fromIndex)

String fulltext = "I would like to create a book reader have create, create "; 
int i = 0; 
String findString = "create"; 
int l = findString.length(); 
while(i>=0){ 

    i = fulltext.indexOf(findString,i+l); 
    //store i to an array or other collection of your choice 
} 
+0

它不能進入​​循環 – ogzd 2013-02-26 15:33:40

+0

你是正確的,固定的。 – Scott 2013-02-26 15:34:09

+1

這可能是一個無限循環? ist應該是'i = fulltext.indexOf(「create」,i +「create」.length());' – A4L 2013-02-26 15:37:07

3

使用接受起始位置的indexOf版本。在循環中使用它,直到它找不到。

String fulltext = "I would like to create a book reader have create, create "; 
String subtext = "create"; 
int ind = 0; 
do { 
    int ind = fulltext.indexOf(subtext, ind); 
    System.out.println("Index at: " + ind); 
    ind += subtext.length(); 
} while (ind != -1); 
+1

這可能是一個無盡的循環? ist應該是'ind = fulltext.indexOf(subtext,i + subtext.length());' – A4L 2013-02-26 15:38:33

+0

總是返回第一個索引=( – 2013-02-26 15:38:46

+1

A4L是正確的。編輯修復錯誤的答案。 – 2013-02-26 15:41:22

1

你可以使用Pattern和Matcher的正則表達式。 Matcher.find()試圖找到下一場比賽,Matcher.start()會給你比賽的開始索引。

Pattern p = Pattern.compile("create"); 
Matcher m = p.matcher("I would like to create a book reader have create, create "); 

while(m.find()) { 
    System.out.println(m.start()); 
} 
相關問題