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

  1. Include the necessary header files:
#include <iostream>
#include <string>
#include <algorithm>
  1. Declare a string variable to store the input string:
std::string str;
  1. Take user input for the string:
std::cout << "Enter a string: ";
std::cin >> str;
  1. Use the sort() function to sort the string:
std::sort(str.begin(), str.end());
  1. 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.