Count frequency of characters in a string

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

No comments:

Post a Comment