給定一個字符串,統計其中每個小寫字母(a-z)出現的次數並輸出。
package com;
import org.junit.Test;
public class StringTest {
@Test
public void test() {
String s = "fdfaacceeeeeeeeeeeegghikkkkkoooo";
count(s);
}
public static void count(String str) {
int[] freq = new int[26]; // a-z 對應 0-25
for (char ch : str.toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
freq[ch - 'a']++;
}
}
for (int i = 0; i < freq.length; i++) {
if (freq[i] > 0) {
System.out.println((char)('a' + i) + " : " + freq[i]);
}
}
}
}
a : 3 c : 2 d : 1 e : 12 f : 2 g : 2 h : 1 i : 1 k : 5 o : 4
public static void countAll(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
}
str.chars() .filter(c -> c >= 'a' && c <= 'z') .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(c -> c, Collectors.counting())) .entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
利用 int[26] 數組映射 a-z 索引是最高效的定制方案;通用字符統計推薦 Map 或 Stream API。