如何计算字符串中字符的频率? [英] How to count frequency of characters in a string?
问题描述
我需要编写某种循环来计算字符串中每个字母的频率。
例如:aasjjikkk将计算2'a',1'',2'j',1'i',3'k'。最终像这样的id最终会在一个地图中以字符作为键,计数作为值。有什么好主意怎么做?
I need to write some kind of loop that can count the frequency of each letter in a string.
For example: "aasjjikkk" would count 2 'a', 1 's', 2 'j', 1 'i', 3 'k'. Ultimately id like these to end up in a map with the character as the key and the count as the value. Any good idea how to do this?
推荐答案
您可以使用java Map并将 char
映射到 INT
。然后,您可以迭代字符串中的字符并检查它们是否已添加到地图中,如果有,则可以增加其值。
You can use a java Map and map a char
to an int
. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.
例如:
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
Integer val = map.get(c);
if (val != null) {
map.put(c, new Integer(val + 1));
}
else {
map.put(c, 1);
}
}
最后你会得到所有的您遇到的字符,您可以从中提取它们的频率。
At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.
或者,您可以使用Bozho的使用Multiset的解决方案并计算总发生次数。
Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.
这篇关于如何计算字符串中字符的频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!