C++ Exercises: Reverse a given string
C++ String: Exercise-1 with Solution
Write a C++ program to reverse a given string.
Pictorial Presentation:
Sample Solution:
C++ Code :
#include <iostream>
#include <string>
using namespace std;
string reverse_string(string str) {
string temp_str = str;
int index_pos = 0;
for (int x = temp_str.length()-1; x >= 0; x--)
{
str[index_pos] = temp_str[x];
index_pos++;
}
return str;
}
int main()
{
cout << "Original string: w3resource";
cout << "\nReverse string: " << reverse_string("w3resource");
cout << "\n\nOriginal string: Python";
cout << "\nReverse string: " << reverse_string("Python");
return 0;
}
Sample Output:
Original string: w3resource Reverse string: ecruoser3w Original string: Python Reverse string: nohtyP
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: C++ String Exercises Home
Next: Write a C++ program to change every letter in a given string with the letter following it in the alphabet (ie. a becomes b, p becomes q, z becomes a).
What is the difficulty level of this exercise?