使用StringTokenizer计算字符数

时间:2012-07-01 00:42:10

标签: java string

我需要编写一个函数来计算字符串中每个字母的频率。

这是一个例子:

我收到了文件:notes.txt消息包括:“你好,这是来自内布拉斯加州的杰克”

当我读取文件时,结果如下:

a:3 H:1 e:2 l:2 等

有人告诉我,我可以使用Stringtokeizer,这是真的吗?

2 个答案:

答案 0 :(得分:1)

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);
}

输出:

{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}

答案 1 :(得分:0)

您可以使用Multiset / Bag数据结构方法。使用Guava看起来像:

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());
}

结果:

[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]