C++ Program to Sort String of Characters
Last Updated :
16 Oct, 2024
Sorting a string means rearranging the characters of the given string in some defined order such as alphabetical order. In this article, we will learn how to sort a string by characters in C++.
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.
Sort String by Characters Using Library Function
In C++, the std::sort() function from STL is a simple and efficient way to sort characters of a string. This function works for both C and C++ style strings.
Syntax of std::sort()
std::sort(first, last, comp);
where first and last are the iterator/pointer to the first and the theoretical character after the last character of the string. comp is the comparator function that defines the sorting order. By default, this function sorts the string in increasing alphabetical order.
Example
C++
// C++ Program to sort a string of characters
// using sort() from STL
#include <bits/stdc++.h>
using namespace std;
int main() {
// C++ Style string
string str1 = "geeksforgeeks";
// C++ Style string
char str2[] = "programming";
int len2 = strlen(str2);
// Sort the strings using std::sort()
sort(str1.begin(), str1.end());
sort(str2, str2 + len2);
cout << str1 << endl;
cout << str2;
return 0;
}
Outputeeeefggkkorss
aggimmnoprr
Time Complexity: O(n * log n), where n is the number of characters in the string.
Auxiliary Space: O(n)
Other Methods to Sort String by Characters in C++
C++ provides many different methods to sort the characters of the given string which are listed below:
Manually Using Counting Sort
We observe that there can only be a total of 26 unique characters in a string (not considering alphabets and uppercase characters). In this case, counting sort algorithm can be more efficient because it works by counting the frequency of each character and then reconstructing the sorted string by positioning them using their cumulative frequency.
C++
// C++ Program to sort a string of characters
// using Counting Sort
#include <bits/stdc++.h>
using namespace std;
// Maximum range of ASCII lowercase alphabets
#define RANGE 26
void countSort(string &str) {
int n = str.length();
// Output array to store sorted string
char out[n + 1];
// Count array to store frequency
int count[RANGE] = {0};
// Store the count of each character
for (int i = 0; i < n; i++) {
count[str[i] - 'a']++;
}
// Modify count array to store cumulative
// position of characters
for (int i = 1; i < RANGE; i++) {
count[i] += count[i - 1];
}
// Building output array based on the
// cumulative positions
for (int i = n - 1; i >= 0; i--) {
out[count[str[i] - 'a'] - 1] = str[i];
count[str[i] - 'a']--;
}
out[n] = '\0';
// Copy the sorted characters back to the original string
for (int i = 0; i < n; i++) {
str[i] = out[i];
}
}
int main() {
string str = "geeksforgeeks";
// Sort the string using Counting Sort
countSort(str);
cout << str << endl;
return 0;
}
Time Complexity: O(k + n), where n is the number of characters in the string.
Auxiliary Space: O(k + n), where k is the number of unique characters.
Using std::multiset
We can also sort the string of characters using std::multiset container as an intermediate which automatically stores the given elements in the increasing order. We can then copy these sorted characters back to our string.
We can change the order of multiset by providing custom comparator at the time of declaration.
C++
// C++ Program to sort a string of characters
// using std::multiset
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
string str = "geeksforgeeks";
// Create a multiset and initialize it using str
multiset<char> m(str.begin(), str.end());
// Copy back the sorted character to the string
// using std::copy
copy(m.begin(), m.end(), str.begin());
cout << str;
return 0;
}
Time Complexity: O(n * log n), where n is the number of characters in the string.
Auxiliary Space: O(n)
We can also use std::priority_queue that implements max heap to store the elements and then pop them one by one and store them in the string in reverse.
Otherwise, we can implement the sorting algorithm of our choice to get better control.
Similar Reads
std::string::compare() in C++ The string::compare() function in C++ is used to compare a string or the part of string with another string or substring. It is the member function of std::string class defined inside <string> header file. In this article, we will learn how to use string::compare() in C++.The different ways to
4 min read
How to sort an Array using STL in C++? Given an array arr[], sort this array using STL in C++. Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: {1, 12, 45, 54, 71, 76} Input: arr[] = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12} Approach: Sorting can be done with the help of sort() function provided in STL. Syntax: sort(arr, arr
1 min read
C++ Program to Implement Suffix Array A suffix array is a data structure which can be used to store all possible suffixes of a given string in the sorted order. It stores the starting indices of the suffixes in lexicographical order. It is similar to trie data structure but is more space efficient then tries.ExampleLet the given string
3 min read
Vector of Strings in C++ In C++, a vector of strings is a std::vector container that stores multiple strings. It is useful when you need to store a collection of string data in a single container and refer to them quickly. In this article, we will learn about the vector of strings and how to create and use it in C++.Table o
3 min read
Sort given sentence on the basis of integer present in every string Given a jumbled sentence as a list of strings, the task is to print the sorted sentence of strings on basis of the presence of a single integer in every string. If two string has the same integer sort them lexicographically. Examples: Input : {"2a", "grea3t", "l3earning", "geeksfor0geeks", "p10latfo
9 min read