Java Program to Count The Frequency of Each Character in a String

In this post we’ll see a Java program to count the frequency of each character in a string. Here two ways of counting the number of times each character appears in a String are given.

  1. Using HashMap where character is the key and count is the value. For every character you need to verify if the key already exists in the HashMap. If it does, increase the count otherwise add it to the map as a new key with count 1.
  2. Another way is using char array where you will have to take the char at the first index of the array and iterate the whole array to check if that char is found again, if yes increment the count. At the end replace() method of the String class is used to remove all the occurrences of that character.

Java program Using HashMap to count the frequency of each character

Output

Using char array and String replace() method

Here is a Java program to count the frequency of each character in a String using char array and String replace() method .

Output

That’s all for the topic Java Program to Count The Frequency of Each Character in a String. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: Java Program to Count Number of Words in a String - KnpCode

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.