Reverse a String in C++

In this tutorial, we will write a C++ Program to Reverse a String. There are three different ways to reverse a string.

  • Using library function, reverse()
  • Using loops instead of reverse()
  • Using recursion

However, using recursion is discussed in the next tutorial, you will get the link down below. Before beginning, you must be familiar with the following topics in C++.


Reverse a String in C++

The program takes user input for the string and then reverses it using various ways.

1. C++ Program to Reverse a String using reverse() function

Question: reverse a string in c++ using library function.

The reverse() is a built-in function provided in C++ to reverse a string. This function is defined in an algorithm header file which needs to be included at the beginning of the program.

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
  string str;

  cout << "Enter the string: ";
  cin >> str;

  reverse(str.begin(), str.end());

  cout << "Reversed String: " << str;

  return 0;
}

Output:

Enter the string: simple2code
Reversed String: edocp2elmis


2. How to Reverse a String in C++ using while loop

Here the program uses a while loop to iterate and reverse the string.

#include <iostream>
using namespace std;

int main()
{
  char str[50], temp;
  int length, i = 0, j;

  cout << "Enter the String: ";
  cin >> str;

  //getting the length of a string
  while (str[i] != '\0')
    i++;

  length = i;
  i = 0;
  j = length - 1;

  //swapping to reverse the string
  while (i < j)
  {
    temp = str[i];
    str[i] = str[j];
    str[j] = temp;

    i++;
    j--;
  }

  cout << "Reversed string " << str;

  return 0;
}

Output:

Enter the String: programs
Reversed string smargorp

You can use strlen() function to calculate the length of a string and use that to iterate using a while loop.


3. Reverse a String in C++ using for loops

Here the program uses a for loop. The program uses strlen() function to calculate the length of a string then uses that value to iterate through the string.

Since you are using one of the string built-in functions, make sure to include string.h header file in a program.

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

int main()
{
  char str[50], temp;
  int length, i = 0, j;

  cout << "Enter the String: ";
  cin >> str;

  //getting the length of a string
  length = strlen(str);
  j = length - 1;

  //swapping to reverse the string
  for (i = 0; i < j; i++, j--)
  {
    temp = str[i];
    str[i] = str[j];
    str[j] = temp;
  }

  cout << "Reversed string " << str;

  return 0;
}

Output:

Enter the String: programs
Reversed string smargorp

You may go through the following program on a string.