how to sort a string in c++
To sort a string in C++, you can use the sort()
function from the <algorithm>
library. Here are the steps to sort a string in C++:
- Include the necessary header files:
#include <iostream>
#include <string>
#include <algorithm>
- Declare a string variable to store the input string:
std::string str;
- Take user input for the string:
std::cout << "Enter a string: ";
std::cin >> str;
- Use the
sort()
function to sort the string:
std::sort(str.begin(), str.end());
- Print the sorted string:
std::cout << "Sorted string: " << str << std::endl;
Here's a complete example:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str;
std::cout << "Enter a string: ";
std::cin >> str;
std::sort(str.begin(), str.end());
std::cout << "Sorted string: " << str << std::endl;
return 0;
}
This program prompts the user to enter a string, sorts it using the sort()
function, and then prints the sorted string.