C++ String Exercises: Reverse a given string
1. Reverse a Given String
Write a C++ program to reverse a given string.
Visual Presentation:

Sample Solution:
C++ Code :
#include <iostream> // Including input/output stream library
#include <string> // Including string library for string manipulation
using namespace std; // Using the standard namespace
// Function to reverse a string
string reverse_string(string str) {
	string temp_str = str; // Creating a temporary string to store the original string
	int index_pos = 0; // Initializing index position to start from the beginning
	// Loop to reverse the string
	for (int x = temp_str.length()-1; x >= 0; x--) // Iterating through the string in reverse order
	{
		str[index_pos] = temp_str[x]; // Reversing the characters and storing in the original string
		index_pos++; // Moving to the next index position
	}
	return str; // Returning the reversed string
}
int main() 
{
	cout << "Original string: w3resource"; // Displaying the original string
	cout << "\nReverse string: " << reverse_string("w3resource"); // Displaying the reversed string
	cout << "\n\nOriginal string: Python"; // Displaying the original string
	cout << "\nReverse string: " << reverse_string("Python"); // Displaying the reversed string
	return 0; // Returning 0 to indicate successful execution
}
Sample Output:
Original string: w3resource Reverse string: ecruoser3w Original string: Python Reverse string: nohtyP
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program that reverses a string using recursion without any library functions.
 - Write a C++ program to reverse a string by swapping its characters in-place using two pointers.
 - Write a C++ program that converts a string to a character array and then reverses it using a for loop.
 - Write a C++ program to reverse a string and then compare it with the original to check for palindromicity.
 
Go to:
PREV : C++ String Exercises Home 
NEXT : Replace Each Letter with the Next in the Alphabet.
C++ Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
