The Wayback Machine - https://web.archive.org/web/20241110195023/https://www.geeksforgeeks.org/reverse-a-string-in-c-cpp-different-methods/
Open In App

Different Methods to Reverse a String in C++

Last Updated : 02 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Reversing the string means the last character will be the first character, second last character will be second character and so on. In this article we will learn the different methods to reverse the string in C++.

Examples

Input: str = “Hello World”
Output: dlroW olleH

Input: str = “Geeks for Geeks”
Output: skeeG rof skeeG

Following are the different methods to reverse the string in C++:

Using std::reverse() Function

C++ STL provides a built-in function std::reverse(), which can be used to reverse the string efficiently.

Syntax

std::reverse(s.begin(), s.end());

where, s is the string to be reversed.

Example

C++
// C++ Program to reverse string using
// std::reverse() method
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s = "Hello World";

    // Using reverse() function to reverse s
    reverse(s.begin(), s.end());

    cout << s;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)

Using Reverse Iterators

In C++, reverse iterators allow the traversal of string in reverse. We can use them to construct temporary reversed version of the string and then assign it to the original string.

Example

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

int main() {
    string s = "Hello World";

    // Creating a temporary reversed string
      // and assigning it to the s
    s = string(s.rbegin(), s.rend());
    
      cout << s;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), for temporary reversed string.

Using a Stack

A stack can also be used to reverse a string due to its LIFO (Last In First Out) property. We can push all characters of the string into a stack and clear the current string. Then we pop characters from the stack and append them to the string one by one, resulting in the reversed string.

Example

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

int main() {
    string s = "Hello World";
    stack<char> st;

    // Push each character of string into stack
    for (char c : s)
        st.push(c);

    // Clear the string
    s.clear();

    // Pop characters from stack and add them to
    // reversed string
    while (!st.empty()) {
        s.push_back(st.top());
        st.pop();
    }

    cout << s;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), for stack.

Using Two Pointer Technique

In two-pointer technique, we use two pointers: one starting at the beginning (left) and one at the end (right) of the string. We move them towards the centre of the string and keep swapping the characters they point till they meet each other.

Example

C++
// C++ Program to reverse a string using two 
// pointer method 
#include <bits/stdc++.h>
using namespace std;

int main() {
    string s = "Hello World";

    // Initialize two pointers: left at start
    //  and right at the end of the string
    int l = 0;
    int r = s.length() - 1;

    // Loop until the two pointers meet in the middle
    while (l < r) {
      
        // Swap characters at position left and right
        swap(s[l], s[r]);

        // Move the left pointer to right
        l++;

        // Move the right pointer to left
        r--;
    }

    cout << s;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(1)

Note: Two pointer technique is implemented in the std::reverse() function.

Using Recursion

The two-pointer technique can also be implemented using recursion though it can be less space efficient and harder to understand.

Example

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

// Function to reverse the string using recursion
void revStr(string &s, int l, int r) {
  
    // Base case: When left and right pointer meet
    if (l >= r)
        return;

    // Swap characters at left and right
    swap(s[l], s[r]);

    // Recursive call to reverse remaining substring
    revStr(s, l + 1, r - 1);
}

int main() {
    string s = "Hello World";

    // Call the recursive function to reverse string
    revStr(s, 0, s.length() - 1);

    cout << s;
    return 0;
}

Output
dlroW olleH

Time Complexity: O(n), where n is the length of string.
Auxiliary Space: O(n), for recursive stack.



Similar Reads

5 Different Methods to Find Length of a String in C++
The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 14Important PointsThe constructor of the String cla
4 min read
Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy func
5 min read
Reverse given range of String for M queries
Given a string S of length N and an array of queries A[] of size M, the task is to find the final string after performing M operations on the string. In each operation reverse a segment of the string S from position (A[i] to N-A[i]+1). Examples: Input: N = 6, S = "abcdef", M = 3, A = {1, 2, 3}Output: "fbdcea"Explanation: After the first operation,
15 min read
Easiest Way to Reverse a String
Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string. What is a reversal of string:Reversing a string is the technique that reverses or changes the order of a given string so that the last
4 min read
Different ways to copy a string in C/C++
Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++. Methods to Copy a String in C/C++1. Using strcpy() We can use the inbuilt function strcpy() from <string.h> header file to copy one string to the other. strcpy() accepts a pointer t
15+ min read
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()substr()find()find_first_of()find_last_of() Let's start
4 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File <string> String Functionalities The
6 min read
Default Methods in C++ with Examples
If we write a class that has no methods in it, and the class does not inherit from another class, the compiler will add six methods to it automatically. The methods which can be automatically generated by the compiler are: Default Constructor: It is equivalent to an empty default constructor. The default constructor is a constructor which can be ca
6 min read
Methods vs. Functions in C++ with Examples
A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the need for writing the same code again and again. It helps programmers in writing modular codes. Methods: A method also works the same as that of function. A method is defined inside a class.
3 min read
C++ Class Methods
Prerequisite: Class in C++ Class is a blueprint of an object, which has data members and member functions also known as methods. A method is a procedure or function in the oops concept. A method is a function that belongs to a class. There are two ways to define a procedure or function that belongs to a class: Inside Class DefinitionOutside Class D
3 min read
Hiding of all Overloaded Methods with Same Name in Base Class in C++
In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters. However, if a derived class redefines the base class member method then all the base class methods with the same name become hidden in the derived class. For example, the following program doesn't compile. Here,
3 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Reverse an array upto a given position
Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Example: Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6} We strongly recommend you to minimize your browser and try this yo
6 min read
forward_list::reverse() in C++ STL
std::forward_list::reverse() is an inbuilt function in CPP STL which reverses the order of the elements present in the forward_list. Syntax: forwardlist_name.reverse()Parameter: The function does not accept any parameter. Return value: The function has no return value. It reverses the forward list. Below program demonstrates the above function: Pro
1 min read
list reverse function in C++ STL
The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. Syntax: list_name.reverse()Parameters: This function does not accept any parameters. Return Value: This function does not return any value. It just reverses the order of elements in the list conta
1 min read
How to traverse a STL map in reverse direction?
Map stores the elements in sorted order of keys. Now if we want to traverse it in reverse order we will use reverse_iterator of map. Syntax: map::reverse_iterator iterator_name; Reverse Iterator of map moves in backward direction on increment. So, we will point the reverse_iterator to the last element of map and then keep on incrementing it until i
8 min read
How to traverse a C++ set in reverse direction
Given a Set, the task is to traverse this Set in reverse order. Examples: Input: set = [10 20 30 70 80 90 100 40 50 60] Output: 100 90 80 70 60 50 40 30 20 10 Input: set = [1 2 3 4 5] Output: 5 4 3 2 1 Approach: To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element
2 min read
Count of integers having difference with its reverse equal to D
Given an integer D, the task is to find the count of all possible positive integers N such that reverse(N) = N + D. Examples: Input: D = 63 Output: 2 Explanation: For N = 18, 18 + 63 = 81, which satisfies the condition N + D = reverse(N). For N = 29, 29 + 63 = 92, which satisfies the condition N + D = reverse(N). Therefore, the required output is 2
13 min read
C++ STL - Vector in Reverse Order
Prerequisite: Vectors in C++ A vector can be printed in reverse order with the following methods: By traversing in the backward direction using indexingBy traversing in the backward direction using begin() and end() functions in C++ STLBy traversing in the backward direction using rbegin() and rend() functions in C++ STL Examples: Input: vector = {
3 min read
C++ STL - Reverse Priority Queue
A priority Queue is an abstract data type that resembles a queue, and each element has a corresponding priority value. Priority queues are built on the top of the max heap and use an array or vector as an internal structure. In C++ STL, by default, the first element of the queue is the greatest of all elements in the queue and elements are in nonin
2 min read
C++ Program For Merging Two Sorted Linked Lists Such That Merged List Is In Reverse Order
Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order). Examples: Input: a: 5->10->15->40 b: 2->3->20 Output: res: 40->20->15->10->5->3->2 Input: a: NULL b: 2->3->20 Output: res: 20->3->2Recommended: Please solve it on "PRACTIC
4 min read
Reverse individual words
Given string str, we need to print the reverse of individual words. Examples: Input : Hello World Output : olleH dlroW Input : Geeks for Geeks Output : skeeG rof skeeG Method 1 (Simple): Generate all words separated by space. One by one reverse word and print them separated by space. Method 2 (Space Efficient): We use a stack to push all words befo
15+ min read
std::reverse() in C++
reverse() is a predefined function in header file algorithm. It is defined as a template in the above-mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n). The C++ Course includes lessons on using std::reverse() effectively to manipulate collections.Note: The range use
2 min read
Print system time in C++ (3 different ways)
First Method Printing current date and time using time() Second Method // CPP program to print current date and time // using time and ctime. #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // declaring argument of time() time_t my_time = time(NULL); // ctime() used to give the present time printf("%s
2 min read
Code valid in both C and C++ but produce different output
There are some syntactical structures that are valid for both C and C++ but different behavior when compiled and run in the both languages. Several differences can also be exploited to create code that compile in both languages but behave differently. For example, the following function will return different values in C and C++: Example Codes valid
2 min read
Swapping of subranges from different containers in C++
A container is a holder object that holds a collection of other objects. They are implemented as class templates, which allows a great flexibility in the types supported as elements. Given some elements in vector and list, swap some of their elements. // C++ program to swap subranges from different containers #include <algorithm> #include
2 min read
Different types of range-based for loop iterators in C++
Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically star
5 min read
Different Ways to Setting Up Environment For C++ Programming in Mac
Xcode is an IDE developed by Apple themselves to develop apps for macOS and iOS or all other Operating Systems that Apple develops. It also has support for C/C++ built-in. Here, finding a C++ IDE for a macOS system is quite easy. To run a program in C++ in Mac we have to install Xcode or command-line tools for Xcode. Ways: Hence, there are two opti
3 min read
Different ways to instantiate an object in C++ with Examples
prerequisite: C++ Classes and Objects Different Ways to Instantiate an Object In C++, there are different ways to instantiate an objects and one of the method is using Constructors. These are special class members which are called by the compiler every time an object of that class is instantiated. There are three different ways of instantiating an
6 min read
Different ways to iterate over a set in C++
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. Syntax: set<datatype> setname; Here,Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc. This article focuses on discussing all the meth
5 min read
Practice Tags :
three90RightbarBannerImg