How to Reverse a String in C++

by | C++, Programming, Tips

Reversing a string means changing the order of the characters in it, such that it reads backwards. There are several ways to reverse a string in C++.

This tutorial will go through the methods for reversing a string in C++ with the help of code examples.


Strings in C++

A C++ string variable contains a collection of characters surrounded by double-quotes. There are two types of strings used in C++.

  • C-strings, which are arrays of type char terminated by the null character \0.
  • Strings that are objects of the Standard C++ Library string class.

Reverse a String Using a Recursive Function

Recursion in C++

A function that calls itself is known as a recursive function, and this technique is known as recursion. The code below shows how recursion works. We call the recursive_function in the main function.

Then the recursive_function makes calls to itself repeatedly until it reaches a stopping condition.

void recursive_func()
{
    ....
    recursive_func();
    ....
}
int main() 
{
    ....
    recursive_func();
    ....
}

Let’s look at the recursive function for reversing a string:

#include <iostream>
using namespace std;
// function prototype
void reverse(const string& a);
int main() {
    // Define string
    string str;
    // Request input from user
    printf("\nEnter the string to reverse: ");
    // Assign input to string using cin
    getline(cin, str);
    printf("\nReverse string is: \n");
    // function call
    reverse(str);
    return 0;
}
// recursive function definition
void reverse(const string& str) {
    // store the size of the string
    size_t numOfChars = str.size();
    if(numOfChars == 1) {
        cout << str << endl;
    }
    else {
        cout << str[numOfChars - 1];
        // function recursion
        reverse(str.substr(0, numOfChars - 1));
    }
}

Let’s run the code to get the result:

Enter the string to reverse: C++ is fun to learn!
Reverse string is: 
!nrael ot nuf si ++C

Reverse a String Using a Built-in Function

We can use the predefined reverse() function, which belongs to the algorithm header file. This approach is more straightforward than the recursive method and is easier to debug. Let’s look at the code:

#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
    // Define string
    string str;
    // Request input from user
    printf("\nEnter the string to reverse: ");
    // Assign input to string using cin
    getline(cin, str);
    printf("\nReverse string is: \n");
    // Reverse str[begin..end]
    reverse(str.begin(), str.end());
    // Print result
    cout << str;
    return 0;
}

Let’s run the code to see the result:

Enter the string to reverse: C++ is fun to learn!
Reverse string is: 
!nrael ot nuf si ++C

Reverse a String Using strlen() on char Array

We can handle the string as a C-String and reverse the character order as follows:

#include<stdio.h>
#include<string.h>
int main() {
    // char type array
    char s[50], t;
    // indices to iterate over char array
    int i = 0, j = 0;
    // Take input from user
    printf("\nEnter the string to reverse :");
    // Assign input to char array    
    fgets(s, 50, stdin);
    // Use strlen() to get length of char array not including the terminating character
    j = strlen(s) - 1;
    // While loop to swap characters at position i and j. Counter i increments and counter j decrements.
    while (i < j) {
        t = s[i];
        s[i] = s[j];
        s[j] = t;
        i++;
        j--;
    }
    // Print result
    printf("\nReverse string is : %s", s);
    return (0);
}

Let’s run the code to get the result:

Enter the string to reverse :C++ is fun to learn!
Reverse string is : 
!nrael ot nuf si ++C

Reverse a String Using Iterative Function In-place conversion

We can iterate over a string and swap elements similar to the C-String approach. However, in this case, we get the length of the string object using length() and iterate over it. Let’s look at the code below:

#include <algorithm>
#include <iostream>
using namespace std;
void strReverse(string& str){
    int n = str.length();
    for (int i = 0; i < n / 2; i++)
        std::swap(str[i], str[n - i - 1]);
}
int main(){
    // Define string
    string str;
    // Take input from user
    printf("\nEnter the string to reverse :");
    // Assign input to string
    getline(cin, str);
    printf("\nReverse string is: \n");
    // Function call
    strReverse(str);
    // Return output   
    cout << str;
    return 0;
}

Let’s run the code to get the output:

Enter the string to reverse :C++ is fun to learn!
Reverse string is: 
!nrael ot nuf si ++C

Reverse a String Using Iterative Function Using Stack

We can reverse a string using the stack data structure. A stack is a linear data structure that follows a particular operation order.

The order may be Last In First Out (LIFO) or First In Last Out (FILO). We can push each character into the stack and then fill the input string by popping characters from the stack in LIFO order until it is empty. Let’s look at an example:

#include <iostream>
#include <stack>
using namespace std;
// Iterative function to reverse a given string.
// string is a reference parameter
void reverse(string &str, int n)
{
    // create an empty stack of characters
    stack<char> s;
    // push each character of the given string into the stack
    for (int i = 0; i < n; i++) {
        s.push(str[i]);
    }
    // start from index 0
    int k = 0;
    // pop characters from the stack in LIFO order until it is empty
    while (!s.empty())
    {
        // assign each character popped from the stack back to the input string
        str[k++] = s.top();
        s.pop();
    }
}
int main()
{
    // Define string
    string str;
    // Take input from user
    printf("\nEnter the string to reverse :");
    // Assign input to string
    getline(cin, str);
    printf("\nReverse string is: \n");
    // Function call
    reverse(str, str.length());
    // Return output   
    cout << str;
    return 0;
  
}

Let’s run the code to get the output:

Enter the string to reverse :C++ is fun to learn!
Reverse string is: 
!nrael ot nuf si ++C

Summary

Congratulations on reading to the end of this tutorial. We have gone through recursive and iterative methods to reverse a string.

For further reading on string manipulation in C++, go to the articles:

How to Convert String to Char Array in C++

How to Find the Length of a String in C++

How to Check if a Vector Contains an Element in C++

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨