String str = "oiwerwwoijjjwwnlamxjswwkxmn2w";
int count = str.length() - str.replace("w", "").length();
// 或正則(需轉義特殊字元)
// int count = str.length() - str.replaceAll("w", "").length();
replace(oldChar, newChar) / replaceAll(regex, replacement) 移除目標字元,長度差即為出現次數。replace 不用正則,**效能更好**,適用於單字元。
// 計數 "ab" 出現次數(不重疊)
int count = (str.length() - str.replace("ab", "").length()) / "ab".length();
for (char c : str.toCharArray()) if (c == 'w') count++; 避免建立新字串,記憶體效率最高。int[] freq = new int[65536]; for (char c : str.toCharArray()) freq[c]++;。