Saturday, February 4, 2023
HomejQuery3 Methods of Reverse a String in C++

3 Methods of Reverse a String in C++ [4 Examples]

Reverse a string in C++

Chances are you’ll use alternative ways for reversing a string in C++. This contains built-in capabilities that you could be use fairly simply and it’s possible you’ll write your personal operate as effectively.

First manner – Utilizing reverse operate instance

  • There’s a built-in operate reverse() that you could be use to reverse a string in C++.
  • That is outlined within the algorithm header file that it’s important to embrace within the C++ file.
  • The reverse operate takes two parameters as proven within the instance under



In this system,

  • A string variable is said and assigned a string containing A-Z.
  • We used the reverse() operate with start and finish parameters
  • The string is displayed earlier than and after utilizing the reverse() operate.

Utilizing for loop with swap() operate

On this instance, the swap() operate is used to reverse a string the place a for loop is used. See the code and output under:



You see, we despatched “Hiya World! C++” to the operate and it reversed the string.

The swap() operate is used to swap the characters.

Study extra concerning the swap operate right here.

Studying string final to first – for loop

On this strategy, a for loop is used and the string is learn from final to first to get the reversed string.

Take a look on the code and output:



The logic is:

  • First, you get the size of the string and assign it to an int-type variable within the for loop.
  • The variable i worth is decremented in every iteration
  • The output exhibits a reverse string, in addition to authentic string, stays the identical

The instance of utilizing some time loop for reversing the string

In case you are a fan of the whereas loop, the identical factor could be achieved as within the above instance by utilizing whereas loop.

See this system under the place the consumer is requested to enter a string to be reversed.

The whereas loop is used to reverse it from final to first and we used getline() operate with cin.

Pattern output:

Reverse string by utilizing do-while loop

And eventually, the identical could be achieved by utilizing a do-while loop as follows:

Pattern output:





Please enter your comment!
Please enter your name here

Most Popular

Recent Comments