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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15092941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:27:30  来源:igfitidea点击:

how to find all first indexes in the string?

java

提问by Max Usanin

I am use this source:

我正在使用这个来源:

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

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

but I find only the first index, how to find all first indexes in the string ? (in this case three index)

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

回答by óscar López

After you've found the first index, use the overloaded version of indexOfthat receives the start index as a second parameter:

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

public int indexOf(int ch, int fromIndex)Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

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

Keep doing that until indexOfreturns -1, indicating that there are no more matches to be found.

继续这样做直到indexOf返回-1,表明没有更多的匹配被找到。

回答by Stephen Ostermiller

Use the version of indexOf that accepts a starting position. Use it in a loop until it doesn't find any more.

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

回答by Sotirios Delimanolis

You can use regex with Pattern and Matcher. Matcher.find()tries to find the next match and Matcher.start()will give you the start index of the match.

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

回答by Scott

You want to create a while loop and use indexof(String str, int fromIndex).

您想创建一个 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
 }