Wednesday, 10 June 2015

Count total number of times each character appears in a String - Java Program

This Java program is for counting the total number of times each character appears in the string.

Here it is done using HashMap provided by Java collection framework. Logic is to read one character at a time from the string and put it in HashMap; character as key, count as value (Initial value will be 1).

With every character that is read from the String check in the HashMap, if it already exists as a key or not. If it exists then increment the count otherwise add the key in HashMap with value 1.

public class CountCharacters {
    
    // method used to count characters in a String
    public void countChars(String message){
        Map<Character, Integer> numCharMap = new HashMap<Character, Integer>();
        for(int i = 0; i < message.length(); i++){
            // Take one character 
            char c = message.charAt(i);
            // We don't need to count spaces
            if(c == ' ')
                continue;
            // If that character is already there in the map
            // then increase the value by 1
            if(numCharMap.containsKey(c)){
                numCharMap.put(c, numCharMap.get(c) + 1);
            }else{
                // otherwise put that character in the map
                // with the value as 1
                numCharMap.put(c, 1);
            }
        }
        // Displaying the map values
        Set<Map.Entry<Character, Integer>> numSet = numCharMap.entrySet();
        for(Map.Entry<Character, Integer> m : numSet){
            System.out.println("Char- " + m.getKey() + " Count " + m.getValue());
        }
    }
    
    public static void main(String[] args) {
        CountCharacters cc = new CountCharacters();
        cc.countChars("I am an Indian");;
    }

}

Output

Char- a Count 3
Char- d Count 1
Char- I Count 2
Char- i Count 1
Char- m Count 1
Char- n Count 3

Values are displayed by looping the HashMap, entrySet is used to iterate the map, which gives the key value pair as Entry object.

That's all for this topic Count total number of times each character appears in a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count number of words in a String
  2. How to find the longest palindrome in the given String
  3. How to add double quotes to a String
  4. How to reverse a string in Java
  5. Reading file in Java 8

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment