LAST UPDATED: APRIL 4, 2022
C++ Program To Display String From Backward
Write own reverse function by swapping characters: One simple solution is to write our own reverse function to reverse a string
// A Simple C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
// Function to reverse a string
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
// Driver program
int main()
{
string str = "hello";
reverseStr(str);
cout << str;
return 0;
}
Using inbuilt “reverse” function: There is a direct function in “algorithm” header file for doing reverse that saves our time when programming.
// A quickly written program for reversing a string
// using reverse()
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "hello";
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
}
Conclusion
Here, in this tutorial, we have learned different approaches of reversing a string or to print the given string from backwards.