Here you will get C++ program to reverse a string. We will learn two ways to do this, using user-defined and inbuilt functions.
The user is asked to enter a string and then the reverse of the string is displayed.
For example:
- Input String: hello
- Output String: olleh
User Defined Function
In this method, we will use a loop to reverse the string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char temp;
cout<<"Enter any string:";
getline (cin, str);
int len = str.length();
for (int i = 0; i < len / 2; i++) {
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
cout << str << endl;
return 0;
}
Output:
Enter any string:i love c++
++c evol i
Inbuilt Function
This method uses the inbuilt function reverse() from the algorithm header file.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str;
cout<<"Enter any string:";
getline (cin, str);
reverse(str.begin(), str.end());
cout << str << endl;
return 0;
}
Output:
Enter any string:The Crazy Programmer
remmargorP yzarC ehT
Comment below if you are facing any difficulty understanding the above program.
I think this logic is good than using multiple for loops ……….
#include
#include
#include
using namespace std;
int main(){
char str1[20],str2[20];
int i=0,len;
cout<<"Enter a String : ";
gets(str1);
len = strlen(str1);
while(len>=0){
str2[i] = str1[–len];
i++;
}
str2[i]='