Mirror of a string in C++ (Reversal of string)

In this tutorial, we will learn how to get the mirror of a string i.e., reversing a string along with its implementation in C++.

Mirror of a string

Mirroring a string means finding the reverse of the string. For example, consider the string “codespeedy”. The mirror of this string is “ydeepsedoc”.

Implementation in C++

Include the string.h header file. This header file contains necessary constructs for handling strings.

#include <iostream> 
#include <string.h> 
using namespace std;

int main ()
    char s[30], temp;
    int i, n;
    cout << "Please, enter a string : ";
    n = strlen(s) - 1;
    for (i = 0; i < n; i++, n--)
    	// swapping
        temp = s[i];
        s[i] = s[n];
        s[n] = temp;
    cout << "Mirror of the string is : " << s;
    return 0;

Let us accept a string from the user which the user expects to be mirrored. We will use the gets() method to accept the string.

Now, let us find out the last index of the string. The last index is the length of the string minus one. The length of the string can be found out by using the strlen() method.

Mirroring a string means the first character should be at the last and the last character should be at the first. From the two ends i.e., front and back of the string, we need to swap the front and back characters. Continue swapping until you reach the middle element.

We can achieve this using a for loop. The variable ‘i’ traversing from the front and the variable ‘n’ traversing from the back.


Please, enter a string : Welcome to codespeedy
Mirror of the string is : ydeepsedoc ot emocleW

Also read, How to compare between string in C++
How to remove digits from string in C++

Leave a Reply