字符串中出现的子字符串

字符串中出现的子字符串

为什么下面的算法没有为我停下来?(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);


慕妹3242003
浏览 336回答 3
3回答

largeQ

最后一行是制造问题。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);

忽然笑

用StringUtils.CountMatch来自阿帕奇公社朗?String str = "helloslkhellodjladfjhello";String findStr = "hello";System.out.println(StringUtils.countMatches(str, findStr));产出:3

潇潇雨雨

你的lastIndex += 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java