Java program to find the counts of each character in a String

Java Program to find character counts in a String :

In this tutorial, we will find the count of each characters in a given string (updated version).

Solution :

1. First get the string input from the user

2. Create one hashmap with key as ‘character’ and value as ‘integer’ . Count of each character will be stored as value with key as the character.

3. Scan the string character by character

4. Check for each character : if no key equalt to the character is available in the hashmap , add one new key as the character and value as 1.

5. If key is available, increment the value by one.

 

import java.util.HashMap;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String line;
        int value;
        Scanner sc = new Scanner(System.in);

        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        System.out.println("Enter a String :");

        line = sc.nextLine();

        for (int i=0; i<line.length(); i++){
            if(map.containsKey(line.charAt(i))){
                value = map.get(line.charAt(i));
                value ++;
                map.put(line.charAt(i),value);
            }else{
                map.put(line.charAt(i),1);
            }
        }


        for ( Character key : map.keySet()){
            System.out.println("Character : '"+key+"' Count :"+map.get(key));
        }

    }

}

 

One Reply to “Java program to find the counts of each character in a String”

  1. Good tutorial on counting chars in a String. The commons.lang.StringUtils library has a countMatches() method that would work well in this example.

Leave a Reply