String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex); // 首次回傳 0
if (lastIndex != -1) count++;
lastIndex += findStr.length(); // 應在迴圈內,但位置錯誤
}
indexOf(str, fromIndex) 從 fromIndex 開始搜尋,包含該索引位置。lastIndex=0,搜尋到索引 0,計數 +1。lastIndex += 5 變為 5,下一次從索引 5 搜尋,正常。indexOf 回傳 -1,lastIndex = -1 + 5 = 4,導致迴圈條件 lastIndex != -1 永真 → 無限迴圈。int lastIndex = 0;
int count = 0;
while (true) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex == -1) break;
count++;
lastIndex += findStr.length(); // 移動到下一個可能位置
}
System.out.println(count); // 輸出 3
if (lastIndex != -1) 區塊內break 明確跳出indexOf 回傳 -1 後仍進行算術運算Pattern pattern = Pattern.compile(Pattern.quote(findStr));
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find()) count++;
更簡潔且自動處理重疊、特殊字元等情況。