Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

How to count the frequency of characters in a string in Java?

1 Answer

0 votes
by (13.1k points)

You can try something like this:
 

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

   }

}

Want to learn Java? Check out the core Java certification from Intellipaat.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...