This post will discuss how to sort characters of a string in C++.

The standard and efficient solution to inplace sort characters of a string is using the std::sort algorithm from header <algorithm>. It is usually implemented using the Introsort algorithm, which is a hybrid of quicksort, heapsort, and insertion sort.

 
The std::sort algorithm accepts an iterator to the initial and final position, and sorts elements in that range in increasing order. A typical invocation of the std::sort algorithm would look like below, to sort a std::string:

Download  Run Code

 
The above two-arg std::sort overload uses the std::less<>() comparison object, which delegates the call to operator<. We can provide the custom comparison function as the third argument to the std::sort function to define the ordering. For example, to sort the string in descending order, use the std::greater<>() function object, which delegates the call to operator>.

Download  Run Code

 
Since C++14, we can skip the template arguments to std::greater function object. i.e., std::greater<>() will work.

Download  Run Code

 
To avoid modifications to the original string, consider making a copy of it and then sorting it. The following program demonstrates this by preserving the original string and sorting the copy:

Download  Run Code

That’s all about sorting the characters of a string in C++.