Group all occurrences of characters according to first appearance | C ++ program to print all occurrences of every character together . ; Since only lower case characters are there ; Function to print the string ; Initialize counts of all characters as 0 ; Count occurrences of all characters in string ; Starts traversing the string ; Print the character till its count in hash array ; Make this character 's count value as 0. ; Driver code
# include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void printGrouped ( string str ) { int n = str . length ( ) ; int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { while ( count [ str [ i ] - ' a ' ] -- ) cout << str [ i ] ; count [ str [ i ] - ' a ' ] = 0 ; } } int main ( ) { string str = " geeksforgeeks " ; printGrouped ( str ) ; return 0 ; }