为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

守候你守候我 2019-03-28 15:19:01
为什么下面的算法不能停止?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);
查看完整描述

5 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

lastIndex = str.indexOf(findStr,lastIndex);

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

查看完整回答
反对 回复 2019-04-28
?
不负相思意

TA贡献1777条经验 获得超10个赞

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

查看完整回答
反对 回复 2019-04-28
?
POPMUISE

TA贡献1765条经验 获得超5个赞

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


查看完整回答
反对 回复 2019-04-28
?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

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


查看完整回答
反对 回复 2019-04-28
?
www说

TA贡献1775条经验 获得超8个赞

代码看起来像这样。

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


查看完整回答
反对 回复 2019-04-28
  • 5 回答
  • 0 关注
  • 533 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号