frequency of characters in string java


In Most of the interview room question or Technical Program is Frequency of Character means In String which you enter how many characters are repeated and count this variable.

So, There are some steps.
1 ) Convert String into a char array.
2 ) We need to two for loops i loop and j loop.
3 ) First, we check  j<i and two characters are same or not.
4 ) Then we check both characters are same or not if it's same then counter variable increment by 1.
5 ) Then the Last condition is if j is equal to the size of a char array. if it's then print character and counter.

Ok. let's check Program of the frequency of character in java.

public class FrequencyCharacter{
               
              public static void main(String args[]){
                     String s = "Hello";
                     char[] c= new char[s.length()];
                     int counter,i,j;
                      int l = c.length;//length of char array..
                    
                      //String Hello store into char[] c ...
                    
                      c = s.toCharArray();//(Step - 1)
                    
                      //(Step - 2)Now, we take i loop...
                    
                      for( i = 0; i<l; i++){
                         //inner loop of j loop.......
                         counter = 0;
                         for( j = 0; j<l; j++){
                               //(Step - 3)
                               
                               if( j < i && c[i] == c[j]){
                                       break; // if condition true then loop is break...
                               }

                               //(Step - 4)
                               
                               if( c[j] == c[i]){
                                     counter++;
                               }

                               //(Step - 5)
                               
                                if( j == l-1){
                                        System.out.println("Character is "+c[i]+" and count by "+counter);
                               }

                         }//end of j loop
                    }//end of i loop
              }
}



Comments