Write a java program to count the occurrence of each character in a string

Java program to count the occurrence of each character in a string. It is a simple java program that uses a count array of size 256 to find the occurrences.

Input:

Enter a string: Astronaut

Output:

The occurrence of each character are:
A: 1
a: 1
n: 1
o: 1
r: 1
s: 1
t: 2
u: 1

Write an algorithm to count the occurrence of each character in a string

  1. First, we will take string input from the user.
  2. Secondly, we will create a count[] array of size 256 where the index of the array denotes the ASCII values of each character and the array values denote the occurrence of that character in the given string.
  3. For this, we will create a for loop which runs from i=0 to i=s.length()-1. As we know, the indices of count array refer to the ASCII value of character, we will increment the count array by 1 each time corresponding to the character ( i.e. count[s.charAt(i)]++ ). The array thus obtained contains the occurrence of each character.
  4. Now, we will loop through the count array from i=0 to i=255. If the value of count[i] has changed i.e. from 0 to any positive no., it means that the character has occurred at least once in the given string. We will now simply print the character corresponding to the index and its occurrence in the given string.
  5. Note:- As the ASCII value of space is 32, we will display it as “Space” for ease of readiness.

Program to count the occurrence of each character in a string:

import java.util.Scanner;
public class CountOccurence 
{
    public static void main(String[] args) 
    {
       Scanner sc=new Scanner(System.in);
        System.out.println("Enter a string:");
       String s=sc.nextLine();
       int count[]=new int[256];
       for(int i=0;i<s.length();i++) count[s.charAt(i)]++;
        System.out.println("The occurrence of each character are:");
       for(int i=0;i<256;i++)
       {
           if(count[i]!=0)
           {
               if(i==32) System.out.println("Space : "+count[i]);
               else System.out.println((char)i+": "+count[i] );
           }       
       }
    }
}

The output of the program to count the occurrence of each character in a string: