如何查找字符串中的所有第一个索引?

时间:2013-02-26 15:29:24

标签: java

我使用这个来源:

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

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

但我只找到第一个索引,如何查找字符串中的所有第一个索引? (在这种情况下是三个指数)

4 个答案:

答案 0 :(得分:8)

找到第一个索引后,使用接收起始索引的重载版indexOf作为第二个参数:

  

public int indexOf(int ch, int fromIndex)返回指定字符第一次出现的字符串中的索引,从指定索引处开始搜索。

indexOf返回-1之前继续这样做,表示找不到更多匹配项。

答案 1 :(得分: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);

答案 2 :(得分:2)

您可以将正则表达式与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());
}

答案 3 :(得分: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
 }
相关问题