Java program to count the occurrence of each character in a string

  • In this Java program, we will have to count the frequency of the occurrence of each character of a string and then print it on the screen.
  • To calculate the frequency of each character, we will take a string from the user as input. We will use the integer array of length 256 to count the frequency of the characters.
  • Start the frequency array element with zero, which means that all the numbers counting at the beginning is zero.
  • Using for loop, crossing the input string and increasing the count of each character of the input string. Finally, cross the frequency table and print the frequency of each character

Java program to count the occurrences of each character


import java.util.*;

class Main

{

static void findCharFrequency(String string)

{

   int counter[] = newint[256];

   int length = string.length();

  for (int i = 0; i < length; i++)

  counter[string.charAt(i)]++;

 char charr[] = newchar[string.length()];

 for (int i = 0; i < length; i++) {

 charr[i] = string.charAt(i);

 int match = 0;

 for (int j = 0; j <= i; j++) 
{

  if (string.charAt(i) == charr[j])

  match++;

}

   if (match == 1)

     System.out.println("frequency of character " +

     string.charAt(i) + " is:" + counter[string.charAt(i)]);

 }

}

public static void main(String[] args)

{

  String string;

  Scanner scan = new Scanner(System.in);

  System.out.println("Enter the String to find frequency :");

  string=scan.nextLine();

 findCharFrequency(string);

}

}


Output:-

 

 

 

 

 


Leave a Reply

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