首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 字串查找子串計數:修復無限迴圈 Bug

     編輯:程式設計綜合問答

錯誤代碼分析

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(); // 應在迴圈內,但位置錯誤
}

核心問題

  1. indexOf(str, fromIndex) 從 fromIndex 開始搜尋,包含該索引位置。
  2. 首次 lastIndex=0,搜尋到索引 0,計數 +1。
  3. lastIndex += 5 變為 5,下一次從索引 5 搜尋,正常。
  4. 但當找不到時,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++;

更簡潔且自動處理重疊、特殊字元等情況。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved