Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Reverse a given string

C++ String: Exercise-1 with Solution

Write a C++ program to reverse a given string.

Pictorial Presentation:

C++ Exercises: Reverse a given string

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:

Flowchart: Reverse a given string.

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?