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

Java 如何查找字符串中的所有第一个索引?,java,Java,我正在使用以下来源: String fulltext = "I would like to create a book reader have create, create "; String subtext = "create"; int i = fulltext.indexOf(subtext); 但是我只找到第一个索引,如何找到字符串中的所有第一个索引?(在本例中为三个索引)找到第一个索引后,使用接收开始索引的重载版本作为第二个参数: public int indexOf(int c

我正在使用以下来源:

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

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

但是我只找到第一个索引,如何找到字符串中的所有第一个索引?(在本例中为三个索引)

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

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


继续执行此操作,直到
indexOf
返回
-1
,表明找不到更多匹配项。

您想创建一个while循环并使用
indexOf(String str,int fromIndex)


使用接受起始位置的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);

您可以将regex与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());
}

这可能是一个无止境的循环??它应该是
i=fulltext.indexOf(“create”,i+create.length())这一个也返回了错误的答案。提示:您的算法应该考虑-1.@james.garriss哦,我明白了,请注意,这些只是示例,用于说明
indexOf
如何工作,而不是完全工作的代码,重点是显示您可以从字符串中的某个索引开始使用它来查找子字符串的进一步出现,很明显,
-1
表示未找到匹配项。这可能是一个无休止的循环??它应该是
ind=fulltext.indexOf(subtext,i+subtext.length())始终返回第一个索引=(
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());
}