// 錯誤:將字串拆為 char 存入 ArrayList
若輸入句子「我愛你中國」,查詢「中國」,程式會逐字比較:「我」==「中國」? 「愛」==「中國」? …永遠不相等。
charAt 比對。indexOf 循環或正則 Pattern/Matcher。String text = "我愛你中國";
String target = "中"; // 單一字元
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == target.charAt(0)) count++;
}
System.out.println(count); // 輸出 1
String text = "中國中國人";
String target = "中國";
int count = 0, idx = 0;
while ((idx = text.indexOf(target, idx)) != -1) {
count++;
idx += target.length(); // 避免重疊計數,若需重疊則 idx++
}
System.out.println(count); // 輸出 2
Map<Character, Integer> freq = new HashMap<>();
for (char c : text.toCharArray()) {
freq.merge(c, 1, Integer::sum);
}
// 輸出:{中=2, 國=2, 人=1}
明確需求是「統計字元」還是「統計子字串」,選擇對應演算法;避免濫用 ArrayList 存放基本型別,優先使用 String 原生方法或 Map 統計。