How to quickly reverse a string in C++?

C++Server Side ProgrammingProgramming

In this section, we will see how to reverse a string very quickly using C++. For reversing there is a built-in function in the algorithm library, called reverse(). This function takes the beginning and the ending pointer of a container, then reverse the elements.

Input: A number string “Hello World”
Output: “dlroW olleH”


Step 1:Take a string
Step 2: reverse it using reverse() function
Step 3: Print the result.
Step 4: End

Example Code

 Live Demo


using namespace std;
main() {
   string my_str = "This is a string to be reversed";

   cout << "Initial state of this string: " << my_str << endl;
   //reverse using the reverse() function for reversing a string

   reverse(my_str.begin(), my_str.end());
   cout << "Final state of this string: " << my_str;


Initial state of this string: This is a string to be reversed
Final state of this string: desrever eb ot gnirts a si sihT
Published on 01-Apr-2019 14:27:48