Hit enter after type your search item

3 Ways of reverse a string in C++ [4 Examples]

Reverse a string in C++

You may use different ways for reversing a string in C++. This includes built-in functions that you may use quite easily and you may write your own function as well.

First way – Using reverse function example

  • There is a built-in function reverse() that you may use to reverse a string in C++.
  • This is defined in the algorithm header file that you have to include in the C++ file.
  • The reverse function takes two parameters as shown in the example below


Output:

CPP-reverse-string

In the program,

  • A string variable is declared and assigned a string containing A-Z.
  • We used the reverse() function with begin and end parameters
  • The string is displayed before and after using the reverse() function.

Using for loop with swap() function

In this example, the swap() function is used to reverse a string where a for loop is used. See the code and output below:


Output:

CPP-reverse-for

You see, we sent “Hello World! C++” to the function and it reversed the string.

The swap() function is used to swap the characters.

Learn more about the swap function here.

Reading string last to first – for loop

In this approach, a for loop is used and the string is read from last to first to get the reversed string.

Have a look at the code and output:


Output:

CPP-reverse-first-last

The logic is:

  • First, you get the length of the string and assign it to an int-type variable in the for loop.
  • The variable i value is decremented in each iteration
  • The output shows a reverse string, as well as original string, remains the same

The example of using a while loop for reversing the string

If you are a fan of the while loop, the same thing can be achieved as in the above example by using while loop.

See the program below where the user is asked to enter a string to be reversed.

The while loop is used to reverse it from last to first and we used getline() function with cin.


Sample output:

CPP-reverse-while-loop

Reverse string by using do-while loop

And finally, the same can be done by using a do-while loop as follows:


Sample output:

CPP-reverse-do-while

 

This div height required for enabling the sticky sidebar