Find the frequency of characters with Java

Configurare noua (How To)

Situatie

To accomplish this task, we will maintain an array called freq with same size of the length of the string. Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element in freq. Finally, iterate through freq to display the frequencies of characters.

For example: Frequency of p in above string is 2.

Backup

  1. public class FrequencyCharacter
  2. {
  3.      public static void main(String[] args) {
  4.         String str = “picture perfect”;
  5.         int[] freq = new int[str.length()];
  6.         int i, j;
  7.         //Converts given string into character array  
  8.         char string[] = str.toCharArray();
  9.         for(i = 0; i <str.length(); i++) {
  10.             freq[i] = 1;
  11.             for(j = i+1; j <str.length(); j++) {
  12.                 if(string[i] == string[j]) {
  13.                     freq[i]++;
  14.                     //Set string[j] to 0 to avoid printing visited character  
  15.                     string[j] = ‘0’;
  16.                 }
  17.             }
  18.         }
  19.         //Displays the each character and their corresponding frequency  
  20.         System.out.println(“Characters and their corresponding frequencies”);
  21.         for(i = 0; i <freq.length; i++) {
  22.             if(string[i] != ‘ ‘ && string[i] != ‘0’)
  23.                 System.out.println(string[i] + “-“ + freq[i]);
  24.         }
  25.     }
  26. }

Output:

Characters and their corresponding frequencies
p-2
i-1
c-2
t-2
u-1
r-2
e-3
f-1

Solutie

Tip solutie

Permanent

Voteaza

(11 din 15 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?