Java program to check frequency of characters in a string

Check frequency of character in a string

Finding the frequency of a character in a string, means we have to check how many times a particular character is present in that string. Here, we have coded a Java Program for the same. Let’s take an example of a string “prepinsta” . In which we have to check that how many times each of the characters gets repeated in the string.

 

Java program to check frequency of characters in a string

Algorithm

  •  Take string input from user and store it in the variable called “str”.
  • After that make freq array having size of length of string.
  • Convert string to char array .
  • Run for loop start from i=0 to str<length() store 1 to freq array.
  • Run j loop start from i=i+1 to j<str.length().
  • check condition if(string[i] == string[j]) then do freq[i]++  and set string[j]=’0′ .
  • After that display frequency of character one by one.

Code in Java

import java.util.Scanner;

public class FrequencyOfCharactersInAString {
   public static void main(String[] args) {
    Scanner sc =new Scanner(System.in);
     System.out.print("Enter String : ");
     String str = sc.nextLine(); 
     int[] freq = new int[str.length()]; 
     int i, j; 

     //Converts given string into character array 
     char string[] = str.toCharArray(); 
     for(i = 0; i <str.length(); i++) { 
        freq[i] = 1; 
          for(j = i+1; j <str.length(); j++) { 
            if(string[i] == string[j]) { 
            freq[i]++; 

           //Set string[j] to 0 to avoid printing visited character 
            string[j] = '0'; 
          } 
       } 
    } 
    //Displays the each character and their corresponding frequency 
    System.out.println("Characters and their corresponding frequencies"); 
    for(i = 0; i <freq.length; i++) { 
       if(string[i] != ' ' && string[i] != '0') 
          System.out.println(string[i] + "-" + freq[i]); 
       } 
   }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter String : prepinsta
Characters and their corresponding frequencies
p-2
r-1
e-1
i-1
n-1
s-1
t-1
a-1