Saturday 4 December 2021

Q14_Java Program to find the frequency of characters

remove_white_space

Java Program to find the frequency of characters

In this program, we need to find the frequency of each character present in the word. Picture perfect

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.

string 1

"picture perfect"

Program

class FrequencyCharacter {

  public static void main(String[] args)   {

    //declare string

   String str1="Remove white spaces";

  int [] freq = new int [str.length()];

  int i, j;

  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]++;

     string[j] = '0';

   }

  }

 }

  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]);

      }

    }

   }

output

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

Theory

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...