Summary: In this tutorial, we will learn different ways to reverse a string in C++ programming language.

Example:

Method 1: Using reverse()

reverse() method available in the algorithm header file can reverse a string in-place without writing any boilerplate code.

All we need to do is to pass the begin and end iterator as arguments to the particular method.

Here is an example in C++, demonstrating the same:

Output:

!dlrow olleH

Method 2: Using Loop

We can also reverse a string using ‘for’ or ‘while’ loop without any built-in funtion.

The idea is to iterate through the characters of the input string in reverse order and concatenate them to a new string.

Reverse a string in C++ Program

To do this, we have to follow the following steps:

  1. Input a string.
  2. for loop from str.length() to 0 in decrementing order.
    1. Concatenate each character to the reverse string i.e., rev = rev + str[i].
  3. Output the reverse string.

Here is the implementation of the steps in C++:

Output:

edoc

Method 3: Using Recusion

We can also reverse a string using recursion in C++. The idea is to extract the characters on each recursive call and reassign them to the string in reverse order during the traceback process.

Here is the implementation of the idea in C++:

Output:

remmargorP licneP

In the reclusive function declaration, we have used the & operator with the string parameter.

By doing so, the string is passed by reference and the changes made on the parameter are reflected by the input string of the main method (i.e. in-place algorithm).

These were some ways to reverse any string in C++ programming. Share with us in the comments section if you know any other such methods.

Leave a Reply

eight − 7 =