Sort string of characters | C ++ 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 wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void sortString ( string & str ) { int charCount [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) charCount [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) for ( int j = 0 ; j < charCount [ i ] ; j ++ ) cout << ( char ) ( ' a ' + i ) ; } int main ( ) { string s = " geeksforgeeks " ; sortString ( s ) ; return 0 ; }