Sort string of characters | Java program to sort a string of characters ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we will do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function
public class SortString { static final int MAX_CHAR = 26 ; static void sortString ( String str ) { int letters [ ] = new int [ MAX_CHAR ] ; for ( char x : str . toCharArray ( ) ) { letters [ x - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { for ( int j = 0 ; j < letters [ i ] ; j ++ ) { System . out . print ( ( char ) ( i + ' a ' ) ) ; } } } public static void main ( String [ ] args ) { sortString ( " geeksforgeeks " ) ; } }