Table of contents
1.
Introduction
2.
What is Reversing a String in C++
3.
Reversing a String in C++ Using recursion
4.
Reversing a String in C++ Using Stack
5.
Reversing a String in C++ Using Inbuilt functions
6.
Reversing a String in C++ Using another String/ Temporary Character
7.
Reversing a String in C++ Using Constructor
8.
Frequently Asked Questions
8.1.
How do you reverse a string?
8.2.
Which inbuilt function is used to reverse a string in C++?
8.3.
How do you reverse a string without a reverse function?
8.4.
Why the string is immutable?
9.
Conclusion
Last Updated: Sep 1, 2024
Easy

Reverse a String in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Reversing a string In C++ involves changing the order of its characters so that the last character becomes the first, the second-last character becomes the second, and so on. 
To reverse a string means to change its order so that the characters that were initially at the end of the string are now at the beginning and vice versa.
For example, if the original string is "ninjas", the reversed string would be "sajnin".
Reversing a string is a common task in programming and can be helpful in various applications such as searching and sorting algorithms.

Reverse a String in C++

In this blog, we will discuss all approaches to reverse a string in C++ with examples and their explanations.

What is Reversing a String in C++

Reversing a string in C++ refers to the process of changing the order of characters in a string so that the last character becomes the first, the second last becomes the second, and so on, until the original first character becomes the last. In other words, it involves rearranging the characters of a string in reverse order.

For example, if we have the string "Hello", the reversed string would be "olleH". The process of reversing a string is often used in various programming scenarios, such as text processing, data manipulation, and algorithmic problem-solving.

In C++, a string is represented by the `std::string` class, which provides various member functions and operators to manipulate and operate on strings. To reverse a string, you can either modify the original string in place or create a new string that contains the characters in reverse order.

Reversing a String in C++ Using recursion

We used recursive functions to reverse a string from the below programs by using different conditions through if statements.

Implementation in C++

#include <bits/stdc++.h>
using namespace std;

/* Function to print reverse of the passed string */
void reverse(string str)
{
    if(str.size() == 0)
    {
        return;
    }
    reverse(str.substr(1));
    cout << str[0];
}
 
int main()
{
    string a = "CodingNinjas";
    reverse(a);
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

sajniNgnidoC
You can also try this code with Online C++ Compiler
Run Code

Reversing a String in C++ Using Stack

In the below code, we are using a stack to reverse the string in C++.

Implementation in C++

// C++ program to reverse a string using stack
#include <bits/stdc++.h>
using namespace std;

// A structure to represent a stack
class Stack
{
	public:
	int top;
	unsigned capacity;
	char* array;
};

// function to create a stack of given
// capacity. It initializes size of stack as 0
Stack* createStack(unsigned capacity)
{
	Stack* stack = new Stack();
	stack->capacity = capacity;
	stack->top = -1;
	stack->array = new char[(stack->capacity * sizeof(char))];
	return stack;
}

// Stack is full when top is equal to the last index
int isFull(Stack* stack)
{ return stack->top == stack->capacity - 1; }

// Stack is empty when top is equal to -1
int isEmpty(Stack* stack)
{ return stack->top == -1; }

// Function to add an item to stack.
// It increases top by 1
void push(Stack* stack, char item)
{
	if (isFull(stack))
		return;
	stack->array[++stack->top] = item;
}

// Function to remove an item from the stack.
// It decreases top by 1
char pop(Stack* stack)
{
	if (isEmpty(stack))
		return -1;
	return stack->array[stack->top--];
}

// A stack based function to reverse a string
void reverse(char str[])
{
	// Create a stack of capacity
	//equal to length of string
	int n = strlen(str);
	Stack* stack = createStack(n);

	// Push all characters of string to stack
	int i;
	for (i = 0; i < n; i++)
		push(stack, str[i]);

	// Pop all characters of string and
	// put them back to str
	for (i = 0; i < n; i++)
		str[i] = pop(stack);
}

int main()
{
	char str[] = "CodingNinajs";

	reverse(str);
	cout << "The reversed string is " << str;

	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

The reversed string is sjaniNgnidoC
You can also try this code with Online C++ Compiler
Run Code

Reversing a String in C++ Using Inbuilt functions

The reverse() function directly reverses the given string, and this function is present in string.h library. The code for this function is inbuilt in the library, we need to just give a string as the input to the function.

Implementation in C++

// using reverse()
#include <bits/stdc++.h>
using namespace std;
int main()
{
	string str = "CodingNinjas";

	// Reverse str[begin..end]
	reverse(str.begin(), str.end());

	cout << str;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

sajniNgnidoC
You can also try this code with Online C++ Compiler
Run Code

Reversing a String in C++ Using another String/ Temporary Character

The idea is to transfer the string to another string in a reverse manner. All we need is the size of the string. The approach is to initialize a character array of the same size and start copying the elements of the input string from the end.

Implementation in C++

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char str[200], strTemp[200];
    int len, i=0;
    cout<<"Enter the String: ";
    gets(str);
    while(str[i]!='\0')
        i++;
    len = i;
    strTemp[len] = '\0';
    len--;
    i = 0;
    while(str[i]!='\0')
    {
        strTemp[len] = str[i];
        i++;
        len--;
    }
    i=0;
    while(strTemp[i]!='\0')
    {
        str[i] = strTemp[i];
        i++;
    }
    cout<<"\nReverse = "<<str;
    cout<<endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Input:

CodingNinjas
You can also try this code with Online C++ Compiler
Run Code

Output:

Reverse = sajniNgnidoC
You can also try this code with Online C++ Compiler
Run Code

Reversing a String in C++ Using Constructor

In the below code, passing reverse iterators to the constructor returns us a reversed string.

Implementation in C++

// A simple C++ program to reverse string using constructor
#include <bits/stdc++.h>
using namespace std;
int main(){

	string str = "CodingNinjas";

	//Use of reverse iterators
	string rev = string(str.rbegin(),str.rend());

	cout<<rev<<endl;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

sajniNgnidoC
You can also try this code with Online C++ Compiler
Run Code

Frequently Asked Questions

How do you reverse a string?

Reversing a string can be done in multiple ways. Some of them are using the reverse() function, using constructor, recursion, and stack.

Which inbuilt function is used to reverse a string in C++?

The “reverse()” function is used to reverse a string in C++. It is present in string.h library.

How do you reverse a string without a reverse function?

To reverse a string, there are many methods like recursion, stacks, constructors in different languages.

Why the string is immutable?

The String itself is immutable in Java. The reason for this is that the = operator for strings is overloaded, takes the string literal as an argument, and then loops through the string literal copying each character into a mutable char array.

Conclusion

In this article, we discussed a basic operation of a string which is reversing a string in C++. We learned about many different methods to do this like using the reverse() function and stack and some of the programs using recursion, constructors in C++, and finally Stack using different strings and characters to reverse the string.

You can refer to our guided paths on Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Live masterclass