Print characters and their frequencies in order of occurrence | Java implementation to print the character and its frequency in order of its occurrence ; function to print the character and its frequency in order of its occurrence ; size of the string ' str ' ; ' freq [ ] ' implemented as hash table ; accumulate frequency of each character in ' str ' ; traverse ' str ' from left to right ; if frequency of character str . charAt ( i ) is not equal to 0 ; print the character along with its frequency ; update frequency of str . charAt ( i ) to 0 so that the same character is not printed again ; Driver program to test above
public class Char_frequency { static final int SIZE = 26 ; static void printCharWithFreq ( String str ) { int n = str . length ( ) ; int [ ] freq = new int [ SIZE ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str . charAt ( i ) - ' a ' ] != 0 ) { System . out . print ( str . charAt ( i ) ) ; System . out . print ( freq [ str . charAt ( i ) - ' a ' ] + " ▁ " ) ; freq [ str . charAt ( i ) - ' a ' ] = 0 ; } } } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; printCharWithFreq ( str ) ; } }