C++ Program to Reverse a String
Write a c++ program to reverse a string. Reverse a string in c++.
C++ program to reverse a string
- Accept a string or sentence from user.
- Calculate Length of string by using strlen() function.
- Use for loop to replace last and first characters. Then second and second last characters and so on.
- Resultant string is the reverse string of original given string.
- Print the reverse string to the screen.
/* C++ program to reverse a string */
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char temp, str[100];
int i, n;
cout << "Enter a string : ";
cin >> str;
n = strlen(str) - 1;
for (i = 0; i < n; i++,n--)
{
temp = str[i];
str[i] = str[n];
str[n] = temp;
}
cout << "\n Reverse String : " << str;
return 0;
}
Output:
Enter a string : computer Reverse String : retupmoc
Comments