Sort Characters Of A String In C++

Sorting a string is considered an organization in an ascending or descending order, or any provided order in C++, which is nothing more than obtaining the strings given in an appropriate order or given order may be expressed as the strings are sorted in the specified order arrangement. A sorting program’s output is a rearranged input or a permutation of that input. In C++, there are several methods for sorting strings by implementing sorting algorithms: bubble sort, insertion sort, STL libraries, etc. These methods sorted the string characters in ascending or decreasing orders.

Methods Of Sorting String And Characters Of A String In C++

There are various sorting strategies available for arranging a string in a certain order. Among them are:

Bubble Sort

One of the simplest sorting algorithms in C++ is bubble sort. The strings are sorted using this approach by comparing the nearby strings or characters in the string. Then, swap them in the provided order, which might be alphabetically arranged in C++.

Insertion Sort

The insertion sort algorithm selects the characters one at a time and inserts them in the appropriate position. Each iteration of the insertion sort method takes a character from the given list and inserts it into the sorted sub-string. The method takes the character and inserts it in the right position depending on the ASCII value while sorting alphabetically.

Standard Library Function

By importing the <algorithm> header file in our code, we can utilize the sort method from the C++ Standard Template Library. Compared to creating the code, using this in-built method is easier and faster.

We can also use std::sort() in C++. The std::sort() is a Standard Template Library (STL) function in C++. The method accepts a beginning and an ending iterator and, by default, is arranged in ascending order. By handing in a comparator operation that returns a Boolean, the method may also be used for specific sorting.

Example 1

The sort function is one of the easiest ways to sort the string character. The only thing required is just to import the standard library of C++. The code begins with importing the standard “stdc++.h” library in the header section. The library contains all the standard library files. The “namespace std” is also included in the code.

After the header section, we have created a void function as “MyString ” and passed a reference string “SortStr” in the constructor. Then, we have invoked the sort() method in the “MyString ” function. The sort() method has the starting iterator and the ending iterator, which sort the string character in ascending order. The sorted string will be printed through the cout statement.

Now, we have the main function in which we have declared a string as “StrVal ” and initialized it. The string “StrVal ” is passed in the function “MyString” for sorting the given string.

using namespace std;
void MyString(string &SortStr)
   sort(SortStr.begin(), SortStr.end());
   cout << SortStr;
int main()
    string StrVal = "ProgrammingLanguage";
    cout << "\n";
    return 0;

The sort() method sorted the string characters in ascending order. The result of ascending order string characters is shown in the image.


We can also sort the string or string characters by using the std::sort method, which is included in the c++ built-in library <algorithm>. The following code has two libraries, “iostream” and “algorithm” in the header section. Through the library “algorithm” we can access the std::sort method.

After the header section, we have the main function in which we have defined a string array as “colors” and initialized it with some words. Then, we have to define an array size equal to “5” in an “ArrSize” of data type integer. Now, utilizing the std::sort method takes an array of “colors” and the array size as an argument to sort the string.

There is a for loop statement in the next line of code, which iterates the loop until the array size “5” for a string array. The cout statement will print the sorted array in ascending order.

#include <iostream>
#include <algorithm>
using namespace std;
int main() {

  string colors[] = {"pink", "grey", "yellow", "blue", "red"};
  int ArrSize = 5;
  std::sort(colors, colors + ArrSize);
  for (int a = 0; a < 5; a++){
  return 0;

The output from the standard library function string shown below is sorted in alphabetical order.

Example 3

An effective strategy would be first to notice that there can only be 26 distinct characters. So, in a hashed array, we may store the number of occurrences of each character from ‘a to ‘z.’ We will just search the hashed array and output the characters from ‘a’ to ‘z’ as they appear several times in the input string. Thus, to implement the code, we have imported a standard library, “stdc++.h” which helps us to sort the specified array.

Now, we have declared the variable “Characters” with the keyword “const” and initialized it with the value “26”. Then, we have a function called “SortStr” which takes the reference of a sorted string as “strx”. In the function, we have created a hash array as “CountChar”. Initially, the starting character count is initialized with zero. After the hash array initialization, we have a for loop statement which traverses the string and increments the character count. The hashed array’s first index represents the character ‘a’; the second represents ‘b,’ etc.

So, for the character’s position in the count of a hash array, we used strx[i]-‘a’. We have a nested loop for traversing and comparing the character through the string. If the variable “j” in the loop is greater than the count character in the variable “i”. The string hash array will traverse and print the characters. In the last lines, we have the main function where we have declared and initialized the string for the function “MyString”.

using namespace std;
const int Characters = 26;
void SortStr(string &Strx)
    int CountChar[Characters] = {0};
    for (int i=0; i<Strx.length(); i++)
    for (int i=0; i<Characters ;i++)
        for (int j=0;j<CountChar[i];j++)
            cout << (char)('a'+i);
int main()
    string MyString = "Welcomefriends";  
    cout <<"\n";
    return 0;

The outcome of the sorted character of the string is displayed on the following terminal screen.

Example 4

In C++ programming, we must ask the user to provide a few names to arrange strings (names) alphabetically (strings). Then, as indicated in the code below, sort these input strings or names alphabetically. We have the bubble sorting algorithm for this illustration. The code has the main function where we have defined a character array “AllName” of array size “5” and character value of “10”. Also, we have another array “Name” of data type string and set the character value to “10”.

Then, we have defined an integer type variable “x” and “y”. The character array will be user input in this code. The user will enter the five-character string of names. Now, we have nested loop statements, and in the nested loop block, we have an if the condition that uses the “strcmp” function to compare two strings. After comparing the strings, we have invoked the “strcpy” function for swapping the string’s names. As a result, we have the sorted alphabetical order of string names.

using namespace std;
int main()
    char AllName[5][10], name[10];
    int x, y;
    cout<<"Enter Names: ";
    for(x=0; x>AllName[x];
    for(x=1; x<5; x++)
        for(y=1; y0)
                strcpy(name, AllName[y-1]);
                strcpy(AllName[y-1], AllName[y]);
                strcpy(AllName[y], name);
    cout<<"\nAlphabetical order of Names :\n";
    for(x=0; x<5; x++)
    return 0;

At first, you have to enter five random names; then, it will sort the string names in alphabetical order. The resultant sorted string names in alphabetical order are displayed below.


We conclude that the character of the string sorting in C++ is accomplished through various sorting algorithms. Here, we explore how to sort a string in C++ with some sorting examples and how to sort a string using a few sorting algorithms. All the implementations of codes are done in Ubuntu 20.04 using the g++ compiler. We hope this article has helped you better grasp the approach of building a Custom Sort function to sort an unordered string of characters and its implementation in C++.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content