C++ Program to Sort String of Characters

Last Updated : 26 Aug, 2026

Sorting a string means arranging its characters in a specific order, such as alphabetical or lexicographical order.

  • std::sort() provides a simple way to sort the characters of a string in ascending order.
  • Other approaches include Counting Sort and std::multiset.

Examples

Input: str = "geeksforgeeks"
Output: "eeeefggkkorss"
Explanation: The characters in the string are sorted in alphabetical order.

Input: str = "programming"
Output: "aggimmnoprr"
Explanation: The characters in the string are sorted in alphabetical order.

Ways to Sort a String

There are several ways to sort the characters of a string in C++:

Sort String Using std::sort()

The std::sort() function from the C++ STL sorts elements in a specified range. It can directly sort the characters of a C++ string or a C-style character array.

C++
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

int main()
{
    // C++ string
    string str1 = "geeksforgeeks";

    // C-style string
    char str2[] = "programming";

    int len2 = strlen(str2);

    // Sort both strings in ascending order
    sort(str1.begin(), str1.end());
    sort(str2, str2 + len2);

    cout << str1 << endl;
    cout << str2;

    return 0;
} 

Output
eeeefggkkorss
aggimmnoprr

Explanation: The program passes the complete range of str1 using begin() and end() to std::sort(). For the character array, the range is specified using the first element and the position just after the last character.

Sort String Using Counting Sort

Counting Sort can be used when the string contains only lowercase English letters. Since there are only 26 possible characters, their frequencies can be stored in a fixed-size array.

C++
#include <iostream>
#include <string>
using namespace std;

void countSort(string& str)
{
    // Frequency array for lowercase letters
    int count[26] = {0};

    // Count each character
    for (char ch : str)
        count[ch - 'a']++;

    // Reconstruct the string in sorted order
    int index = 0;

    for (int i = 0; i < 26; i++) {
        while (count[i]--)
            str[index++] = char('a' + i);
    }
}

int main()
{
    string str = "geeksforgeeks";

    countSort(str);

    cout << str;

    return 0;
}

Output
eeeefggkkorss

Explanation: The program counts the frequency of every lowercase character and stores the counts in the count array. It then traverses this array from 'a' to 'z' and reconstructs the string using the stored frequencies.

Sort String Using std::multiset

A std::multiset stores elements in sorted order and allows duplicate characters. It can therefore be used as an intermediate container for sorting the characters of a string.

C++
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main()
{
    string str = "geeksforgeeks";

    // Store characters in sorted order
    multiset<char> ms(str.begin(), str.end());

    // Copy sorted characters back to the string
    copy(ms.begin(), ms.end(), str.begin());

    cout << str;

    return 0;
} 

Output
eeeefggkkorss

Explanation: The multiset automatically keeps all inserted characters in ascending order while preserving duplicates. std::copy() then copies the sorted characters from the multiset back into the string.

Sort String Using std::priority_queue

A priority_queue can also be used to sort characters by storing them in a heap and extracting them according to their priority. For ascending order, a min-heap is used so that the smallest character is removed first.

C++
#include <iostream>
#include <queue>
#include <string>
using namespace std;

int main()
{
    string str = "geeksforgeeks";

    // Min-heap for characters
    priority_queue<char, vector<char>, greater<char>> pq;

    // Insert all characters into the heap
    for (char ch : str)
        pq.push(ch);

    // Extract characters in sorted order
    for (int i = 0; i < str.size(); i++)
    {
        str[i] = pq.top();
        pq.pop();
    }

    cout << str;

    return 0;
} 

Output
eeeefggkkorss

Explanation: Each character is inserted into a min-heap, which keeps the smallest character at the top. Characters are then removed one by one and placed back into the string, producing the sorted order.

Sort String Using a Manual Sorting Algorithm

The characters can also be sorted without using STL sorting containers by implementing a basic sorting algorithm such as Bubble Sort.

C++
#include <iostream>
#include <string>
using namespace std;

void bubbleSort(string& str)
{
    int n = str.length();

    // Compare adjacent characters
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - i - 1; j++)
        {
            // Swap if characters are out of order
            if (str[j] > str[j + 1])
                swap(str[j], str[j + 1]);
        }
    }
}

int main()
{
    string str = "geeksforgeeks";

    bubbleSort(str);

    cout << str;

    return 0;
} 
Try It Yourself
redirect icon

Output
eeeefggkkorss

Explanation: The program compares adjacent characters and swaps them whenever they are in the wrong order. After each pass, the largest remaining character moves toward the end of the string, and repeated passes produce the sorted string.

Comment