C++ Program to Sort String in Ascending Order
Sorting strings in ascending order is a very basic task in C++, especially when you are dealing with text processing or when you need to organize data in a more readable format. Let’s see an example of how to sort a string in ascending order using the sort() function from the C++ Standard Library.
C++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Sanjana";
// Convert string to all lower case to ensure uniform sorting
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::tolower(c); });
// Sorting the string in ascending order
std::sort(str.begin(), str.end());
// Output the sorted string
std::cout << "Sorted string in ascending order: " << str << std::endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Sorted string in ascending order: aaajnns
In this code :
- Include Necessary Headers: We include <iostream> for input/output operations, <string> for string operations, and <algorithm> for the sort() function.
- String Initialization: A string variable str is initialized with the value "Sanjana".
- Case Normalization: The string is converted to lowercase to ensure that the sorting does not get affected by character casing.
- Sorting: The sort() function is used to rearrange the characters of the string in ascending order. It modifies the string in place.
- Output: The sorted string is then printed to the console.
Note: This method is efficient and very easy for sorting characters within a single string. It utilizes the powerful features of the C++ Standard Library to perform sorting with minimal code.
C++ Program to Sort String in Descending Order
Sorting a string in descending order in C++ can be done efficiently with the help of the sort() function combined with a custom comparator. This approach is very useful for cases where you want to display data in reverse order, or when the application logic requires elements to be processed from the largest to the smallest.
C++
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Rahul";
// Convert string to all upper case to emphasize sorting by descending order
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::toupper(c); });
// Sorting the string in descending order using a lambda function as a comparator
std::sort(str.begin(), str.end(), [](char a, char b) {
return a > b;
});
// Output the sorted string
std::cout << "Sorted string in descending order: " << str << std::endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Sorted string in descending order: URLHA
In this code :
- Include Necessary Headers: The necessary headers are included to handle input/output operations and to utilize the sort() function.
- String Initialization: We start with the string "Rahul".
- Case Conversion: The string is converted to uppercase, which helps sort when case sensitivity might impact the results.
- Sorting with Comparator: The sort() function is called with a custom lambda comparator that sorts the characters in descending order.
- Output: Finally, the sorted string is printed, showing the characters sorted from Z to A.
Note: This technique is useful when you need to sort strings based on specific criteria that the default sorting behavior does not support.
C++ Program to Sort String (Names) in Alphabetical Order
Sorting names alphabetically is a common requirement for applications that manage user data, organize lists, or need to display names in an ordered format. In C++, this can be achieved with the help of the sort() function from the Standard Library to sort an array or vector of strings.
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::vector<std::string> names = {"Rinki", "Harsh", "Sanjana", "Rahul", "Ravi"};
// Sorting the names in alphabetical order
std::sort(names.begin(), names.end());
// Output the sorted names
std::cout << "Names sorted in alphabetical order:" << std::endl;
for (const std::string& name : names) {
std::cout << name << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Names sorted in alphabetical order:
Harsh
Rahul
Ravi
Rinki
Sanjana
In this code :
- Include Necessary Headers: We include <iostream> for output operations, <vector> to use the vector container, <algorithm> for the sorting function, and <string> for string handling.
- Vector Initialization: A vector of strings names is initialized with a list of names.
- Sorting: The sort() function is applied to the vector, which sorts the strings in alphabetical order by default.
- Output: The sorted list of names is printed line by line to show the alphabetical ordering.
Note: This method is simple and uses C++ Standard Library features to achieve the desired result without extra coding for comparison logic.
C++ Program to Sort String by Length
Sorting strings by their length is useful in scenarios where the order of data processing depends on the size of the elements, like text analysis, data summarization, or when prioritizing shorter or longer strings for computational efficiency. In C++, this can be easily done by using the sort() function along with a custom comparator to define the sorting criteria based on string length.
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main() {
std::vector<std::string> words = {"Rinki", "Harsh", "Sanjana", "Rahul", "Sinki"};
// Sorting the strings by length using a custom comparator
std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
return a.length() < b.length();
});
// Output the sorted words by length
std::cout << "Words sorted by length:" << std::endl;
for (const std::string& word : words) {
std::cout << word << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Words sorted by length:
Rinki
Harsh
Rahul
Sinki
Sanjana
In this code :
- Include Necessary Headers: As usual, we include headers for input/output operations, vector usage, algorithm functions, and string operations.
- Vector Initialization: A vector word is initialized with strings of varying lengths.
- Sorting with Comparator: The sort() function is used with a lambda function as a comparator, which sorts the strings based on their length.
- Output: The program outputs the words sorted by length, showcasing how the custom comparator helps organize the data based on the string size.
Note: This method uses the flexibility of C++'s STL to sort based on customized criteria, which makes it highly adaptable to specific application needs.
Frequently Asked Questions
Can I sort strings in C++ without using the std::sort() function?
Yes, you can implement your own sorting algorithms like bubble sort or selection sort to sort strings in C++.
Is it possible to sort strings in C++ based on custom criteria?
Yes, you can provide a custom comparator function to std::sort() to define your own sorting criteria for strings.
How do I sort strings in C++ in a case-insensitive manner?
To sort strings in a case-insensitive manner, you can convert them to lowercase or uppercase before sorting using functions like std::tolower() or std::toupper().
Conclusion
In this article, we learned about different methods to sort strings in C++ using built-in functions and libraries. We sorted strings in ascending order, descending order, and alphabetically. Moreover, we provided proper code examples of every method which might be helpful in better understanding.
You can also check out our other blogs on Code360.