字符串中子字符串的出现

问题

为什么以下算法不会停止? (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);

#1 热门回答(166 赞)

如何从Apache Commons Lang使用StringUtils.countMatches

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

那输出:

3

#2 热门回答(99 赞)

YourlastIndex += findStr.length();被放置在括号外,导致无限循环(当没有发现时,lastIndex始终为findStr.length())。

这是固定版本:

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);

#3 热门回答(79 赞)

更短的版本。 ;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);