Reverse string in c++

Problem

A typical interview question is to describe an algorithm to reverse a string of characters.

Reverse string

Solution

We need one pass through the characters of the string to get the string length or use a built in function to get that. Once the length of the string is found then one for loop can be used to switch the first character with the last character and the second character with the one before the last character and so on until the string is reversed in place. The number of iterations needed is half the string length. If the string has odd number of characters then the character in the middle of the string is not going to be switched with any character and will stay in its place.

Reverse string code

Here is an example C++ code to do that

Reverse string using recursion solution

We can write a recursive reverse string function to reverse a string. The stopping condition occurs when the string is one character in length in such case we just return that string otherwise we return string concatenation constructed from the first character and the recursive reverse of the rest of the characters. For example Reverse(“ABCD”) = Reverse(“BCD”) + “A”

Reverse string recursive method

Here is a Java reverse string program to do that

Another solution

Another variation of the first solution is to use bitwise XOR operation instead of using a temporary variable when switching characters. Actually this is another interview question in which they ask how to swap two variables without using a temporary variable.

Code

Here is a demo code in C++

Add a Comment

Your email address will not be published. Required fields are marked *