Reverse a String in C++2 min read

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.

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.

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.

Output:

Enter the String: programs
Reversed string smargorp

You may go through the following program on a string.


MORE

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …
Read More

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More