猿问

字符串中出现的子串的问题

为什么下面的算法不能停止?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);


守候你守候我
浏览 534回答 5
5回答

眼眸繁星

lastIndex = str.indexOf(findStr,lastIndex);返回 findStr 子字符串在 str 字符串中第一次出现处的 索引 ,从指定的 lastIndex 索引开始。因为lastIndex=0;所以第一次查找得到的索引还是0。应该把下面的 lastIndex+=findStr.length();放到while循环中;这样不会死循环了。

不负相思意

lastIndex+=findStr.length(); str.indexof() 检索到字符串返回字符串的位置 因此str中有次字符串 所以lastIndex永远不等于-1所以是个死循环

POPMUISE

你这个每次进去就是在查hello lastIndex永远为0嘛

扬帆大鱼

lastIndex = str.indexOf(findStr,lastIndex); //确定没有错误????

www说

代码看起来像这样。    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

相关分类

Java
我要回答