C++ Program to Reverse a String | Program to Reverse a String in C++
What is reversing a String?
Reversing a string means changing the positions of the characters in such a way that the last character comes in the first position, second last on the second position and so on.
There are so many ways to reverse a string we will see it one by one.
1. C++ Program to Reverse a String Using Built-in Function
In this program, we will use inbuilt library function called as reverse[begin..end] which reverses the string and print that string on the screen.
Output:

2. Reverse a String Using for loop
In this program, we will use for loop to reverse a string.
Output:

In the above program, we have given input string as “Learnprogramo programming made simple”. After executing the compiler will print the reverse of the input string.
3. Reverse a String Using While Loop
In this program, we will use while loop to do the reverse of a string. After executing this program the compiler will ask the user to enter the string that user want to make the reverse of. After giving input the compiler will print output on the screen.
Output:

4. C++ Program to Reverse a String Using Recursion
The program is said to be recursive if and only if the function can call itself directly or indirectly. In this program, we will declare a recursive function which can reverse an input string.
Output:

In the above program, the reverse() function is recursive. This function prints the last character of the string (numofChars-1). Every array starts with zero so we have use -1.
substr() gives the string up to second last character and it is again passed to the reverse() function.
When the reverse() function is called again then second last character is printed because the string contains one character less than from the last.
Now one character from the last is cut off from the string again and then passed to the reverse() function.
This process continues until the length of the string equal to 1 when the final character is printed and at last the loop ends.
5. Using function
In this program, we will declare user-defined function to reverse a string.
Output:

In the above program, we have declared user-defined function reverse_String() to reverse a string.
6. Reverse a String in C++ Using Iterators
The unique way to loop through the characters of a string to backwards is by using reverse iterators. The iterators are of type read-only so it is must use const reverse iterators which are returned by std::string::crbegin and std::string::crend.
std::string::crbegin points to the last character of the string and std::string::crend which is points to the first character of the string.
Output:

Post a Comment