2013-02-26 74 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()); 
} 
相关问题