Group all occurrences of characters according to first appearance - GeeksforGeeks

26 Aug, 2019
Given a string of lowercase characters, the task is to print the string in a manner such that a character comes first in string displays first with all its occurrences in string.
Examples:
Input : str = "geeksforgeeks"
Output:  ggeeeekkssfor
Explanation: In the given string 'g' comes first 
and occurs 2 times so it is printed first
Then 'e' comes in this string and 4 times so 
it gets printed. Similarly remaining string is
printed.

Input :  str = "occurrence"
output : occcurreen 

Input  : str = "cdab"
Output : cdab

This problem is a string version of following problem for array of integers.
Group multiple occurrence of array elements ordered by first occurrences
Since given strings have only 26 possible characters, it is easier to implement for strings.
Implementation:1- Count the occurrence of all the characters in given string using an array of size 26.2- Then start traversing the string. Print every character its count times.
C++
Java
Python3
C#
// C++ program to print all occurrences of every character// together.# include<bits/stdc++.h>using namespace std;  // Since only lower case characters are thereconst int MAX_CHAR = 26;  // Function to print the stringvoid printGrouped(string str){    int n = str.length();      // Initialize counts of all characters as 0    int  count[MAX_CHAR] = {0};      // Count occurrences of all characters in string    for (int i = 0 ; i < n ; i++)        count[str[i]-'a']++;      // Starts traversing the string    for (int i = 0; i < n ; i++)    {        // Print the character till its count in        // hash array        while (count[str[i]-'a']--)            cout << str[i];          // Make this character's count value as 0.        count[str[i]-'a'] = 0;    }}  // Driver codeint main(){    string str = "geeksforgeeks";      printGrouped(str);      return 0;}
// Java program to print all occurrences of every character// together.  class Test{    // Since only lower case characters are there    static final int MAX_CHAR = 26;          // Method to print the string    static void printGrouped(String str)    {        int n = str.length();               // Initialize counts of all characters as 0        int  count[] = new int[MAX_CHAR];               // Count occurrences of all characters in string        for (int i = 0 ; i < n ; i++)            count[str.charAt(i)-'a']++;               // Starts traversing the string        for (int i = 0; i < n ; i++)        {            // Print the character till its count in            // hash array            while (count[str.charAt(i)-'a']!=0){                System.out.print(str.charAt(i));                count[str.charAt(i)-'a']--;            }                   // Make this character's count value as 0.            count[str.charAt(i)-'a'] = 0;        }    }          // Driver method    public static void main(String args[])    {        String str = new String("geeksforgeeks");                   printGrouped(str);    }}
# Python3 program to print all occurrences# of every character together.  # Since only lower case characters are thereMAX_CHAR = 26  # Function to print the stringdef printGrouped(string):    n = len(string)      # Initialize counts of all characters as 0    count = [0] * MAX_CHAR      # Count occurrences of all characters in string    for i in range(n):        count[ord(string[i]) - ord("a")] += 1      # Starts traversing the string    for i in range(n):          # Print the character till its count in        # hash array        while count[ord(string[i]) - ord("a")]:            print(string[i], end = "")            count[ord(string[i]) - ord("a")] -= 1          # Make this character's count value as 0.        count[ord(string[i]) - ord("a")] = 0  # Driver codeif __name__ == "__main__":    string = "geeksforgeeks"    printGrouped(string)  # This code is contributed by# sanjeev2552
// C# program to print all // occurrences of every // character together.using System;  class GFG{    // Since only lower case     // characters are there    static int MAX_CHAR = 26;          // Method to print     // the string    static void printGrouped(String str)    {        int n = str.Length;              // Initialize counts of        // all characters as 0        int []count = new int[MAX_CHAR];              // Count occurrences of         // all characters in string        for (int i = 0 ; i < n ; i++)            count[str[i] - 'a']++;              // Starts traversing        // the string        for (int i = 0; i < n ; i++)        {            // Print the character             // till its count in            // hash array            while (count[str[i] - 'a'] != 0)            {                Console.Write(str[i]);                count[str[i] - 'a']--;            }                  // Make this character's             // count value as 0.            count[str[i] - 'a'] = 0;        }    }          // Driver code    public static void Main()    {        string str = "geeksforgeeks";        printGrouped(str);    }}  // This code is contributed by Sam007
ggeeeekkssfor

This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
sanjeev2552
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews