C++ Examples

C++ Program - Reverse a given String



In C++, the reverse of a given string can be found out by using below mentioned methods.

Method 1: Using iteration

In the example below, the string called MyString is reversed using ReverseString() function. Two variables l and r are created which initially points to first and last character of the string. If l is less than r, then the characters of MyString at indices l and r swapped. After swapping, l is increased by one and r is decreased by one until they cross each other. Finally, MyString will contain the reversed value of the initial string.

#include <iostream>
using namespace std;

static void ReverseString(string MyString) {
  int l = 0;
  int r = MyString.length() - 1;

  while(r > l){
    //swapping characters at indices l and r
    char c = MyString[l];
    MyString[l] = MyString[r];
    MyString[r] = c;
    
    l++;
    r--;
  }
  cout<<MyString<<"\n";
}

int main() {
  ReverseString("Hello World");
  ReverseString("Programming is fun");
  ReverseString("Reverse this string");
  return 0;
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 2: Using Recursion

The above result can also be achieved using recursive function. Consider the example below:

#include <iostream>
using namespace std;

void ReverseString(char *MyString) {
  if(*MyString) {
    ReverseString(MyString + 1);
    cout<<*MyString;
  }
}

int main() {
  char a[] = "Hello World";
  char b[] = "Programming is fun";
  char c[] = "Reverse this string";

  ReverseString(a);
  cout<<endl;
  
  ReverseString(b);
  cout<<endl;

  ReverseString(c);
  cout<<endl;

  return 0;
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR

Method 3: Printing the string in reverse order

The same can be achieved by printing the string in reverse order. Consider the example below:

#include <iostream>
using namespace std;

static void ReverseString(string MyString) {
  int last = MyString.length() - 1;

  for(int i = last; i >= 0; i--) {
    cout<<MyString[i];
  }
  cout<<"\n";
}

int main() {
  ReverseString("Hello World");
  ReverseString("Programming is fun");
  ReverseString("Reverse this string");
  return 0;
}

The above code will give the following output:

dlroW olleH
nuf si gnimmargorP
gnirts siht esreveR