如何为indexOf创建for循环(String str,int fromIndex)

时间:2016-12-21 22:06:14

标签: java

我需要这段代码来搜索指定的字符串,当它找到一个输出时,然后继续寻找更多。

  int FoundPsn = sample.indexOf("quick", 0);
  System.out.print("sample.indexOf(\"quick\") = " + FoundPsn);

2 个答案:

答案 0 :(得分:2)

尝试类似的东西:

    String sample = "quick, that was quick, and maybe quicker!";
    int foundPsn = 0;
    int startSearch = 0;
    String search = "quick";
    while ((foundPsn = sample.indexOf(search, startSearch)) >= 0){
        System.out.println("sample.indexOf(\"quick\") = " + foundPsn);
        startSearch = foundPsn + search.length();
    }

答案 1 :(得分:0)

工作方法指数:

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
The returned index is the smallest value k for which:

 k >= fromIndex && this.startsWith(str, k)

如果不存在这样的k值,则返回-1。

Sourdes Java doc:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)

你可以做的是保持循环,直到它达到-1之类。

int FoundPsn = sample.indexOf("quick");
while(FoundPsn != -1) {
    System.out.println("sample.indexOf(\"quick\") = " + FoundPsn);
    FoundPsn = sample.indexOf("quick", FoundPsn+1);
}

注意:如果您只搜索一个字符,并且恰好是最后一个字符,那么这将使索引超出范围。