字符串中出現(xiàn)的子字符串為什么下面的算法沒有為我停下來?(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貢獻(xiàn)2039條經(jīng)驗 獲得超8個贊
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貢獻(xiàn)1806條經(jīng)驗 獲得超5個贊
String str = "helloslkhellodjladfjhello";String findStr = "hello";System.out.println(StringUtils.countMatches(str, findStr));
3

瀟瀟雨雨
TA貢獻(xiàn)1833條經(jīng)驗 獲得超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
提交
取消