Open In App

Different Methods to Reverse a String in C++

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The reversing of a string is nothing but simply substituting the last element of a string to the 1st position of the string.

string-reverse

Different Methods to Reverse a String in C++ are:

  • Making our own reverse function 
  • Using ‘inbuilt’ reverse function 
  • Using Constructor
  • Using a temp file

1. Making a Custom Reverse Function For Swapping Characters

  •  Using a first to last approach ‘for’ loop

CPP




// C++ program to reverse a string 
// using first to last approach
// 'for' loop
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners
    for (int i = 0; i < n / 2; i++)
        swap(str[i], str[n - i - 1]);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}


Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)
Auxiliary Space: O(1)

  • Using a first to last Approach with while loop 

C++




// C++ program to reverse a string 
// using while loop
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int len = str.length();
    int n = len-1;
    int i = 0;
    while(i<=n){
        //Using the swap method to switch values at each index
        swap(str[i],str[n]);
        n = n-1;
        i = i+1;
  }
  
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}


Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)
Auxiliary Space: O(1)

  •  Using a Last to First Approach ‘for‘ Loop  

C++




// C++ program to demonstrate reverse
// of a string using Last to First
// Approach 'for' Loop
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverse(string str)
{
    for (int i = str.length() - 1; i >= 0; i--)
        cout << str[i];
}
  
// Driver code
int main(void)
{
    string s = "GeeksforGeeks";
    reverse(s);
    return (0);
}


Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)
Auxiliary Space: O(1)

  • Using a Last to First Approach ‘while’ Loop

C++




// C++ program to demonstrate reverse
// of a string using Last to First
// Approach 'while' Loop
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverse(string str)
{
    int len = str.length();
    int n = len; 
    while(n--)
        cout << str[n];
}
  
// Driver code
int main(void)
{
    string s = "GeeksforGeeks";
  
    reverse(s);
    return (0);
}


Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)
Auxiliary Space: O(1)

 

1. Using recursion Function with two pointer approach

Recursion functions are used for iterating to different indexes of the string.

C++




// C++ program to reverse a string 
// using recursion
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str, int n, int i)
{
      
  if(n<=i){return;}
//  Swapping the character 
  swap(str[i],str[n]);
  reverseStr(str,n-1,i+1);
  
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str, str.length()-1, 0);
    cout << str;
    return 0;
}


Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(N)

2. Using one pointer approach in recursion

Below is the implementation of the code:

C++




//C++ program to reverse a string using recursion
#include <iostream>
using namespace std;
void getreverse(string &str, int i)
{
    if (i > (str.length() - 1 - i))
    {
        return;
    }
    swap(str[i], str[str.length() - i - 1]);
    i++;
    getreverse(str, i);
}
int main()
{
    string name = "geeksforgeeks";
  
    getreverse(name, 0);
    cout << name << endl;
    return 0;
}
//code contributed by pragatikohli


Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(N)

3. Using the inbuilt “reverse” Function

There is a direct function in the “algorithm” header file for doing reverse that saves our time when programming.

// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin, 
BidirectionalIterator end);

CPP




// C++ program to illustrate the
// reversing of a string using 
// reverse() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str = "geeksforgeeks";
  
    // Reverse str[begin..end]
    reverse(str.begin(), str.end());
  
    cout << str;
    return 0;
}


Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

4. Reverse a String Using the Constructor 

Passing reverse iterators to the constructor returns us a reversed string. 

CPP




// C++ program to reverse
// string using constructor
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str = "GeeksforGeeks";
  
    // Use of reverse iterators
    string rev = string(str.rbegin(), str.rend());
  
    cout << rev << endl;
    return 0;
}


Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

5. Using a Temporary String

CPP




// C++ program to demonstrate
// reversing of string 
// using temporary string
#include <bits/stdc++.h>
using namespace std;
int main()
{
  
    string str = "GeeksforGeeks";
    int n = str.length();
    
    // Temporary string to store the reverse
    string rev;
    
    for (int i = n - 1; i >= 0; i--)
        rev.push_back(str[i]);
  
    cout << rev << endl;
    return 0;
}


Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

How could we get the reverse of a const string?

To get the reverse of a const string we have to first declare a ‘const string’ in a user-defined function following which we have declared then use the following algorithm for the calling of the desired objects.

“const reverseConstString = function(string) { return string.split("").reverse().join("")” 

Example: 

C++




// C++ program to get reverse of a const string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse string and return
// reverse string pointer of that
char* reverseConstString(char const* str)
{
    // find length of string
    int n = strlen(str);
  
    // create a dynamic pointer char array
    char* rev = new char[n + 1];
  
    // copy of string to ptr array
    strcpy(rev, str);
  
    // Swap character starting from two
    // corners
    for (int i = 0, j = n - 1; i < j; i++, j--)
        swap(rev[i], rev[j]);
  
    // return pointer of the reversed string
    return rev;
}
  
// Driver code
int main(void)
{
    const char* s = "GeeksforGeeks";
    printf("%s", reverseConstString(s));
    return (0);
}


Output

skeeGrofskeeG

Time Complexity: O(N)
Auxiliary Space: O(N)

Using Stack Data Structure

C++




// C++ Program to reverse a string
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s = "GeeksforGeeks";
    stack<char> st;
    for (char x : s)
        st.push(x);
    while (!st.empty()) {
        cout << st.top();
        st.pop();
    }
    return 0;
}


Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(N)

This article is contributed by Priyam kakati, Ranju Kumari, Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article at write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up

Next Article

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
Taking String input with space in C (4 Different Methods)
We can take string input in C using scanf("%s", str). But, it accepts string only until it finds the first space. There are 4 methods by which the C program accepts a string with space in the form of user input.Let us have a character array (string) named str[]. So, we have declared a variable as char str[20]. Method 1 : Using getsSyntax : char *ge
2 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Different methods to initialize a Linked List
Like arrays, a Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. They include a series of connected nodes. Here, each node stores the data and the address of the next node. There are two methods to copy the linked list into another linked list
15+ 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 &lt;algorithm&gt;. 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
Analysis of Different Methods to find Prime Number in Python
If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them. Going by defin
7 min read
Program to count digits in an integer (4 Different Methods)
Given a number N, the task is to return the count of digits in this number. Example: Simple Iterative Solution to count digits in an integerThe integer entered by the user is stored in the variable n. Then the while loop is iterated until the test expression n != 0 is evaluated to 0 (false).   We will consider 3456 as the input integer.   After the
10 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
three90RightbarBannerImg