在文本處理中,統計子串在主串中的出現次數是常見需求。本文提供基於正則表達式與基於 indexOf 循環的兩種實現,並分析性能差異。
public static int countByRegex(String src, String target) {
int count = 0;
Pattern pattern = Pattern.compile(Pattern.quote(target)); // 轉義特殊字符
Matcher matcher = pattern.matcher(src);
while (matcher.find()) count++;
return count;
}
優點:代碼簡潔,支持正則模式;
缺點:編譯 Pattern、創建 Matcher 開銷大,短文本或高頻調用性能較弱。
public static int countByIndexOf(String src, String target) {
if (target.isEmpty()) return 0;
int count = 0, index = 0;
while ((index = src.indexOf(target, index)) != -1) {
index += target.length(); // 避免重疊匹配,若需重疊改為 index++
count++;
}
return count;
}
優點:無額外對象創建,純字節/字符比較,性能極佳;
注意:index += target.length() 為非重疊匹配,若需重疊(如 "aaa" 中 "aa" 出現 2 次),改為 index++。
indexOf;Pattern/Matcher;String.split(target, -1).length - 1,但會創建數組,內存開銷大。