字符串中出现的子字符串为什么下面的算法没有为我停下来?(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
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);

忽然笑
TA贡献1806条经验 获得超5个赞
String str = "helloslkhellodjladfjhello";String findStr = "hello";System.out.println(StringUtils.countMatches(str, findStr));
3

潇潇雨雨
TA贡献1833条经验 获得超4个赞
lastIndex += findStr.length();
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);
添加回答
举报
0/150
提交
取消