Bill Bill - 4 years ago 265
Java Question

counting frequency of characters in a string

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? im stuck.

Answer Source

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 it's value. For example

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(new Character(c));
   if(val != null){
     map.put(c, new Integer(val + 1));

At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.

Alternativly you can use Bozho's solution of using a Multiset and counting the total occurances.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download