Program to reverse a string (Iterative and Recursive)


The reverse() is a pre-installed and predefined header file, which is used to define as a template in a process in a C++ environment. The method is able to reverse the elements from last to first manner in a range for any value container. For this process the time complexity is O(n). Lets assume, we have a string declared as str[] with some data elements and now the task is to perform reverse process on this string to get the final outcome.

Here is a general example of the process −

Input string is here : S = "ARBRDD"
Output After The Process : S = "DDRBRA"
Input string is here : S = "Right Now I Am Here In Kolkata!"
Output After The Process : S = "!atakloK nI ereH mA I woN thgiR"

Algorithm to perform the reversal process on a particular string

In this possible algorithm, we are going to perform the reversal process on a particular string in a C++ environment. With this algorithm, we will build some C++ syntax to learn about the problem statement in an efficient manner.

  • Step 1 − Start the process.

  • Step 2 − Declare the input output stream.

  • Step 3 − Import the built-in classes and declared functions.

  • Step 4 − Construct and declare a string.

  • Step 5 − Populate the string with some value.

  • Step 6 − Call a recursive or an iterative function to reverse the string.

  • Step 7 − If the declared string is null print the whole string.

  • Step 8 − Or, if there is only one value print the whole string again.

  • Step 9 − Else, if there is multiple character values; call the recursive function and perform the string reverse process.

  • Step 10 − Print the value as the reverse string.

  • Step 11 − Terminate the process.

Syntax to perform the reversal process on a particular string

char str1[100], *ptr;
   int len1 = 0, i;
   char ch;
   printf("Enter the string to apply the process:\n");
   scanf("%[^\n]s", str1);
   ptr = str1;
   len1 = strlen(str1);
   printf("Using the process of iteration:\n");
   for (i = len1 - 1; i >= 0;i--){
      ch = str1[i];
      printf("%c", ch);
  }
   printf("Using the process of recurssion:\n");
   disp_str1_rec(ptr);
}
void disp_str1_rec(char *stng){
   char ch;
   if (*stng != '\0'){
      ch = *stng;
      stng++;
      disp_str1_rec(stng);
      printf("%c", ch);
   }
   else
   return;

In this possible syntax, we will perform the reversal process on a particular string in a C++ environment. With these particular syntax, we are heading towards some C++ programs to get a broad view about the problem statement.

Approaches to Follow

  • Approach 1 − C++ program to reverse a string using stack, iteration, double pointers, reverse(), std::reverse() and C++ STL methods.

  • Approach 2 − C++ program to reverse a string using recursion, recursive stack, fibonacci series, reference parameter, reference parameter methods and doubly linked list.

Approach 1: Using Stack, Iteration, Double Pointers, Reverse(), Std::reverse() and C++ STL Methods

Use of a Stack Method

In this possible approach, we are going to build and apply a stack to print a reverse string from the primary string.

void reverse(string& str){
   reverse(str.begin(), str.end());
}
void reverse(char *str){
   reverse(str, str + strlen(str));
}
int main(){
   string str = "ENTER THE INPUT STRING HERE";
   reverse(str);
   cout << "Reverse of the given std::string is here after the process " <<
str << endl;
   char s[] = "ENTER THE INPUT STRING HERE";
   reverse(s);
   cout << "Reverse of the given C-string is " << s;

Example

//C++ program to reverse a string using stack
#include <bits/stdc++.h>
using namespace std;
void recursiveReverse(string &str){
   stack<char> st;
   for (int i=0; i<str.length(); i++)
   st.push(str[i]);
   for (int i=0; i<str.length(); i++) {
      str[i] = st.top();
      st.pop();
   }
}
int main(){
   string str = "NABDNIAKHDLOKDDRBRA";
   recursiveReverse(str);
   cout << str;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of the Iteration Method

In this possible approach, we are going to apply the iteration method to print a reverse string from the primary string.

Example

//C++ program to reverse a string by using iteration
#include <bits/stdc++.h>
using namespace std;
void reverseStr(string& str){
   int n = str.length();
   for (int i = 0; i < n / 2; i++)
   swap(str[i], str[n - i - 1]);
}
int main(){
   string str = "NABDNIAKHDLOKDDRBRA";
   reverseStr(str);
   cout << str;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of Iteration Method With two Pointers

In this possible approach, we are going to apply the iteration method by using for two pointers to print a reverse string from the primary string.

Example

//C++ program to reverse a string by using iteration with two pointers
#include <bits/stdc++.h>
using namespace std;
void reverseStr(string& str){
   int n = str.length();
   for (int i=0, j=n-1; i<j; i++,j--)
   swap(str[i], str[j]);
}
int main(){
   string str = "NABDNIAKHDLOKDDRBRA";
   reverseStr(str);
   cout << str;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of Reverse() Method

In this possible approach, we have applied the reverse() method function to print a reverse string from the primary string.

Example

//C++ program to reverse a string by using the reverse() method
#include<bits/stdc++.h>
using namespace std;
int main(){
   string str = "NABDNIAKHDLOKDDRBRA";
   reverse(str.begin(),str.end());
   cout << str;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of Std:reverse() Method

In this possible approach, we will apply the std::reverse() method to print a reverse string from the primary string.

Example

//C++ program to reverse a string by using the std::reverse() method
#include <algorithm>
#include <iostream>
#include <string>
int main(){
   std::string str = "NABDNIAKHDLOKDDRBRA";
   std::reverse(str.begin(),str.end());
   std::cout << str << std::endl;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of ‘reverse()’ in C++ STL Method

In this possible approach, we have applied the inbuilt method ‘reverse()’ in C++ STL method function to print a reverse string from the primary string.

Example

//C++ program to reverse a string by using the inbuilt method ‘reverse()’ in C++ STL method
#include <bits/stdc++.h>
using namespace std;
int main(){
   string str = "NABDNIAKHDLOKDDRBRA";
   reverse(str.begin(), str.end());
   cout << str;
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Approach 2: Using Recursion, Recursive Stack, Fibonacci Series, Reference Parameter, Reference Parameter Methods and Doubly Linked List

Use of the Recursion Method

In this possible approach, we will apply the recursion method to print a reverse string from the primary string.

void reverse(const string& a);
int main(){
   string str;
   cout << " INPUT STATEMENT FOR THE PROCESS" << endl;
   getline(cin, str);
   reverse(str);
   return 0;
}
void reverse(const string& str){
size_t numOfChars = str.size();
if(numOfChars == 1) {
   cout << str << endl;
}
else {
cout << str[numOfChars - 1];
reverse(str.substr(0, numOfChars - 1));

Example

//C++ program to reverse a string by using the process of recursion
#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
   if(str.size() == 0){
      return;
   }
   reverse(str.substr(1));
   cout << str[0];
}
int main(){
   string a = "NABDNIAKHDLOKDDRBRA";
   reverse(a);
   return 0;
}

Output

ARBRDDKOLDHKAINDBAN

Use of the Recursive Stack Method

In this possible approach, we are going to build and apply a recursive stack to apply the recursion method. With this we can print a reverse string from the primary string.

Example

//C++ program to reverse a string using recursion with a recursive stack
#include <bits/stdc++.h>
using namespace std;
void reverse(char *str, int index, int n){
   if(index == n){
      return;
   }
   char temp = str[index];
   reverse(str, index+1, n);
   cout << temp;
}
int main(){
   char a[] = "NABDNIAKHDLOKDDRBRA";
   int n = sizeof(a) / sizeof(a[0]);
   reverse(a, 0, n);
   return 0;
}

Output

.ARBRDDKOLDHKAINDBAN

Use of the Fibonacci Series

In this possible approach, we have applied the fibnacci series to print a reverse string from the primary string.

Example

//C++ program to reverse a string using recursion with a fibonacci series
#include <bits/stdc++.h>
using namespace std;
void fibo(int n, int a, int b){
      if (n > 0){
      fibo(n - 1, b, a + b);
      cout << a << " ";
   }
}
int main(){
   int N = 10;
   fibo(N, 0, 1);
   return 0;
}

Output

34 21 13 8 5 3 2 1 1 0

Use of the String as a Reference Parameter

In this possible approach, we will apply the reference parameter method to print a reverse string from the primary string in a C++ environment.

Example

//C++ program to reverse a string using recursion where a string acts like a reference parameter
#include <iostream>
#include <algorithm>
using namespace std;
void reverse(string &str, int k){
   static int i = 0;
   if (k == str.length()) {
      return;
   }
   reverse(str, k + 1);
   if (i <= k) {
      swap(str[i++], str[k]);
   }
}
int main(){
   string str = "I AM GOING TO KASHMIR TODAY";
   reverse(str, 0);
   cout << "Reverse of the given string is here. Have a look ->" << str;
   return 0;
}

Output

Reverse of the given string is here. Have a look ->YADOT RIMHSAK OT GNIOG MA I

Use of the String as Like the Reference Parameter

In this possible approach, we are going to declare a string acts like a reference parameter with a swaping process. By using this method the user will be able to print a reverse string from the primary string.

Example

//C++ program to reverse a string using recursion where a string acts like a reference parameter with a swaping process
#include <iostream>
#include <algorithm>
using namespace std;
void reverse(string &str, int l, int h){
   if (l < h){
      swap(str[l], str[h]);
      reverse(str, l + 1, h - 1);
   }
}
int main(){
   string str = "Right Now I Am Here In Srinagar!";
   reverse(str, 0, str.length() - 1);
   cout << "Reverse of the given string is here. Have A Look ->" << str;
   return 0;
}

Output

Reverse of the given string is here. Have A Look ->!raganirS nI ereH mA I woN thgiR

Use of the Doubly Linked List

In this possible approach, we will construct and apply a doubly linked list to print a reverse string from the declared primary string in a C++ environment.

Example

//C++ program to reverse a string using recursion with a doubly linked list
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *next, *prev;
};
Node* getNode(int data){
   Node* new_node = new Node;
   new_node->data = data;
   new_node->next = new_node->prev = NULL;
   return new_node;
}
void push(Node** head_ref, Node* new_node){
   new_node->prev = NULL;
   new_node->next = (*head_ref);
   if ((*head_ref) != NULL)
   (*head_ref)->prev = new_node;
   (*head_ref) = new_node;
}
Node* Reverse(Node* node){
   if (!node)
   return NULL;
   Node* temp = node->next;
   node->next = node->prev;
   node->prev = temp;
   if (!node->prev)
   return node;
   return Reverse(node->prev);
}
void printList(Node* head){
   while (head != NULL) {
      cout << head->data << " ";
      head = head->next;
   }
}
int main(){
   Node* head = NULL;
   push(&head, getNode(16));
   push(&head, getNode(1997));
   push(&head, getNode(10));
   push(&head, getNode(07));
   push(&head, getNode(2001));
   cout << "The Original List Is Here: ";
   printList(head);
   head = Reverse(head);
   cout << "\nThe Reversed Linked List Is Here: ";
   printList(head);
   return 0;
}

Output

The Original List Is Here: 2001 7 10 1997 16
The Reversed Linked List Is Here: 16 1997 10 7 2001

Conclusion

Today in this article we have learned about how to implement the process to construct and apply the various method to print a reversed string from the promary data set in a C++ environment. With the above mentioned logics, syntax and algoritm; we have tried to build some C++ codes to solve the problem statement in an efficient manner.

Updated on: 27-Dec-2023

41 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements