Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods to Sort String in C++
2.1.
1. Using the Standard Template Library (STL)
2.2.
C++
2.3.
2. Custom Comparison Functions
2.4.
C++
2.5.
3. Bubble Sort Algorithm
2.6.
C++
3.
C++ Program to Sort String in Ascending Order
3.1.
C++
4.
C++ Program to Sort String in Descending Order
4.1.
C++
5.
C++ Program to Sort String (Names) in Alphabetical Order
5.1.
C++
6.
C++ Program to Sort String by Length
6.1.
C++
7.
Frequently Asked Questions
7.1.
Can I sort strings in C++ without using the std::sort() function?
7.2.
Is it possible to sort strings in C++ based on custom criteria?
7.3.
How do I sort strings in C++ in a case-insensitive manner?
8.
Conclusion
Last Updated: Aug 23, 2024
Easy

Sort String in C++

Author Ravi Khorwal
0 upvote

Introduction

Sorting is a fundamental but important concept in programming that arranges elements in a specific order. In C++, sorting strings is a common task that can be done in many different ways. Whether you need to sort strings in ascending order, descending order, alphabetically, or by length, C++ provides built-in functions & libraries to make the process easier. 

Sort String in C++

In this article, we'll discuss different methods to sort strings in C++ with proper code implementation to make them easier to understand.

Methods to Sort String in C++

Sorting strings in C++ can be achieved using multiple techniques, each suited for different scenarios. These methods are crucial for implementing efficient and effective sorting mechanisms in your programs. Here, we'll discuss three primary methods: using the Standard Template Library (STL), custom comparison functions, and the bubble sort algorithm. Each method has its advantages and disadvantages. We need to decide the method as per the requirement of our usage.

1. Using the Standard Template Library (STL)

The STL provides several functions that can be used to sort data. For sorting strings, the `sort()` function from the `<algorithm>` header is commonly used. This function is versatile and supports sorting in both ascending and descending order through the use of custom comparators.


For Example:
 

  • C++

C++

#include <iostream>

#include <string>

#include <algorithm>

int main() {

   std::string str = "coding";

   std::sort(str.begin(), str.end());

   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: cdgino

 

2. Custom Comparison Functions

For more control over the sorting process, you can define custom comparison functions. This method allows you to sort strings based on various criteria, like case sensitivity, or lexicographical order.

For Example:

  • C++

C++

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

bool caseInsensitiveCompare(const std::string &a, const std::string &b) {
std::string lowerA, lowerB;
std::transform(a.begin(), a.end(), std::back_inserter(lowerA), ::tolower);
std::transform(b.begin(), b.end(), std::back_inserter(lowerB), ::tolower);
return lowerA < lowerB;
}

int main() {
std::vector<std::string> names = {"Rahul", "Harsh", "Rinki"};
std::sort(names.begin(), names.end(), caseInsensitiveCompare);
std::cout << "Strings sorted case-insensitively:" << std::endl;
for (const auto &name : names) {
std::cout << name << std::endl;
}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Strings sorted case-insensitively:
Harsh
Rahul
Rinki

3. Bubble Sort Algorithm

Although this is not the most efficient for large data sets, the bubble sort algorithm is a simple way to understand the sorting technique. It can be very helpful for understanding the swapping of elements.

For Example

  • C++

C++

#include <iostream>
#include <string>

void bubbleSort(std::string &str) {
int n = str.length();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (str[j] > str[j+1])
std::swap(str[j], str[j+1]);
}

int main() {
std::string str = "sanjana";
bubbleSort(str);
std::cout << "Sorted string using bubble sort: " << str << std::endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Sorted string using bubble sort: aaajnns

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++

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++

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++

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++

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.

Live masterclass