如何计算字符串中字符的频率? [英] How to count frequency of characters in a string?

查看:32
本文介绍了如何计算字符串中字符的频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写某种循环来计算字符串中每个字母的出现频率.
例如:aasjjikkk"会计算 2 'a', 1 's', 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆