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

Example:

Input:  code
Output: edoc

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:

#include <iostream>
#include<algorithm>
using namespace std;

int main() {
    string str = "Hello world!";
    reverse(str.begin(), str.end());
    cout << str;
    return 0;
}

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

#include <iostream>
using namespace std;
 
int main()
{   
    //Input string
    string str = "code";
    
    //Initialize reverse with null string value
    string rev = "";
    
    //Iterate input string in revrese order
    for(int i=str.length()-1; i>=0; i--){
        //concatenate characters to the reverse
        rev = rev + str[i];  
    }
    
    cout << rev;
    return 0;
}

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

#include <iostream>
using namespace std;

//recursive function
void reverse(string &str, int i){
    //Base condition - when index exceeds string length
    if(i == str.length())
        return;
    
    //extract character
    char ch = str[i];
    //recusively call for next character
    reverse(str, i+1);
    //reassign in reverse order
    str[str.length()-i-1] = ch;
}
 
int main()
{   
    //Input string
    string str = "Pencil Programmer";
    
    //start recirsive funtion from first index
    reverse(str, 0);
    
    //output the string
    cout << str;
    return 0;
}

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

14 − 4 =