我需要编写一个函数来计算字符串中每个字母的频率。
这是一个例子:
我收到文件:notes.txt 消息包括:“你好,这是来自内布拉斯加州的杰克”
当我阅读文件时,结果如下:
a: 3 H: 1 e: 2 l: 2 等
有人告诉我可以使用 Stringtokeizer,这是真的吗?
You could use a Multiset/Bag data structure approach. Using Guava it would look like:
public static void main(String... a) {
final String str = "Hello this is Jack from Nebraska";
final Builder<Character> b = ImmutableMultiset.builder();
for (char c : str.toCharArray())
b.add(c);
System.out.println(b.build());
}
Results in:
[H, e x 2, l x 2, o x 2, x 5, t, h, i x 2, s x 3, J, a x 3, c, k x 2, f, r x 2, m, N, b]
public static void main(String... args) {
String str = "Hello this is Jack from Nebraska";
Map<Character, Integer> frequencies = new HashMap<Character, Integer>();
for (char c : str.toCharArray()) {
if (!frequencies.containsKey(c))
frequencies.put(c, 1);
else
frequencies.put(c, frequencies.get(c) + 1);
}
System.out.println(frequencies);
}
Output:
{f=1, =5, e=2, b=1, c=1, a=3, o=2, N=1, l=2, m=1, H=1, k=2, h=1, J=1, i=2, t=1, s=3, r=2}