子字符串在字符串中的出现次数

新手上路,请多包涵

为什么以下算法对我来说没有停止? (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);

原文由 bobcom 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 373
2 个回答

最后一行造成了一个问题。 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);

原文由 codebreach 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 Apache Commons Lang 中的 StringUtils.countMatches 怎么样?

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

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

输出:

 3

原文由 A_M 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题