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

字符串中出现的子字符串

字符串中出现的子字符串

慕妹3242003 2019-06-21 13:03:31
字符串中出现的子字符串为什么下面的算法没有为我停下来?(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);
查看完整描述

3 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

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


查看完整回答
反对 回复 2019-06-21
?
忽然笑

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

StringUtils.CountMatch来自阿帕奇公社朗?

String str = "helloslkhellodjladfjhello";String findStr = "hello";System.out.println(StringUtils.countMatches(str, findStr));

产出:

3


查看完整回答
反对 回复 2019-06-21
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

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


查看完整回答
反对 回复 2019-06-21
  • 3 回答
  • 0 关注
  • 335 浏览

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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