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
String C/C++ Programs C program to swap two StringsC Program to Sort an array of names or stringsC Program to Check if a Given String is PalindromeC/C++ Program for Return maximum occurring character in the input stringC/C++ Program for Remove all duplicates from the input string.C/C++ Program for Print all the duplicate
3 min read
C++ Program to compare two string using pointers Given two strings, compare the strings using pointers Examples: Input: str1 = geeks, str2 = geeks Output: Both are equal Input: str1 = hello, str2 = hellu Output: Both are not equal As their length are same but characters are different The idea is to dereference given pointers, compare values and ad
1 min read
How to Sort an Array of Strings Using Pointers in C++? In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done. The task is to sort a given array of strings using pointers. Example
2 min read
How to Compare Two Substrings in a Character Array in C++? In C++, character arrays are used to store a sequence of characters also known as strings. A Substring is a continuous sequence of characters within a string. In this article, we will learn how we can compare two substrings in a character array in C++. Examples: Input: string: "Hello World" Substrin
2 min read
C++ Program For Insertion Sort Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++
3 min read
Kth most frequent Character in a given String Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e'
6 min read
Sort an array of strings based on the given order Given an array of strings words[] and the sequential order of alphabets, our task is to sort the array according to the order given. Assume that the dictionary and the words only contain lowercase alphabets. Examples: Input: words = {"hello", "geeksforgeeks"}, order = "hlabcdefgijkmnopqrstuvwxyz" Ou
7 min read
C++ Program To Find Longest Common Prefix Using Sorting Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read
Sorting strings from the text file Given a text file "file.txt" that consists of strings, the task is to sort all the strings in alphabetical order in that text file. Approach: The idea is to use the concept of File Handling and a text file(say file.txt) that contains all the strings. Below are the steps: Create the file using fopen(
6 min read
Convert String to Char Array in C++ In C++, we usually represent text data using the std::string object. But in some cases, we may need to convert a std::string to a character array, the traditional C-style strings. In this article, we will learn how to convert the string to char array in C++.ExamplesInput: str = "geeksforgeeks"Output
4 min read