一尘不染

Java字符串中子字符串的出现

java

为什么以下算法对我来说不停止?(str是我要搜索的字符串,findStr是我要寻找的字符串)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr,lastIndex);

    if( lastIndex != -1)
        count++;

    lastIndex += findStr.length();
}

System.out.println(count);

阅读 293

收藏
2020-02-28

共1个答案

一尘不染

最后一行造成了问题。lastIndex永远不会为-1,所以会有无限循环。可以通过将代码的最后一行移到if块中来解决此问题。

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

    lastIndex = str.indexOf(findStr,lastIndex);

    if(lastIndex != -1){
        count ++;
        lastIndex += findStr.length();
    }
}
System.out.println(count);
2020-02-28