我需要編寫一個函數來計算字符串中每個字母的頻率。使用StringTokenizer計數字符
這是一個例子:
我收到了文件:notes.txt包含消息:「您好,這是來自內布拉斯加州的傑克」
當我讀文件,這是結果:
一:3 H:1 E:2 1:2 等
有人告訴我,我可以使用Stringtokeizer,這是真的嗎?
我需要編寫一個函數來計算字符串中每個字母的頻率。使用StringTokenizer計數字符
這是一個例子:
我收到了文件:notes.txt包含消息:「您好,這是來自內布拉斯加州的傑克」
當我讀文件,這是結果:
一:3 H:1 E:2 1:2 等
有人告訴我,我可以使用Stringtokeizer,這是真的嗎?
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}
你可以使用一個多集/包的數據結構的方法。使用番石榴它看起來像:在
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]
這是真的。還有很多其他的方法可以做到這一點。你有什麼嘗試? – Jeffrey
你能否提供一些你自己的代碼?我們不會爲你做所有事情。 –
[寫入字符串中的信息]的可能的重複(http://stackoverflow.com/questions/11303174/writing-information-in-a-string) – Joey