How to Reverse a String in C++: Simple Methods Explained
To reverse a string in C++, you can use the
std::reverse function from the algorithm header, which reverses the string in place. Alternatively, you can create a new reversed string by iterating from the end to the beginning of the original string.Syntax
The common way to reverse a string in C++ is using the std::reverse function from the algorithm library. It takes two iterators: the start and the end of the string range to reverse.
std::reverse(str.begin(), str.end());reverses the entire stringstrin place.
cpp
std::reverse(str.begin(), str.end());
Example
This example shows how to reverse a string using std::reverse. It prints the original string and the reversed string.
cpp
#include <iostream> #include <string> #include <algorithm> int main() { std::string str = "hello world"; std::cout << "Original string: " << str << std::endl; std::reverse(str.begin(), str.end()); std::cout << "Reversed string: " << str << std::endl; return 0; }
Output
Original string: hello world
Reversed string: dlrow olleh
Common Pitfalls
One common mistake is trying to reverse a string without using iterators or modifying the original string incorrectly. For example, using a loop to swap characters manually but messing up indices can cause errors.
Also, forgetting to include the <algorithm> header will cause a compilation error when using std::reverse.
cpp
#include <iostream> #include <string> int main() { std::string str = "hello"; // Wrong: swapping without correct indices for (int i = 0; i < str.size() / 2; ++i) { char temp = str[i]; str[i] = str[str.size() - i - 1]; str[str.size() - i - 1] = temp; } std::cout << str << std::endl; // This will reverse correctly // Right way: use std::reverse #include <algorithm> std::reverse(str.begin(), str.end()); std::cout << str << std::endl; // Correct reversed string return 0; }
Output
olleh
hello
Quick Reference
- std::reverse: reverses string in place using iterators.
- Manual loop: swap characters from start and end moving inward.
- Include
<algorithm>forstd::reverse. - Strings are mutable in C++ so you can change them directly.
Key Takeaways
Use std::reverse from to reverse strings easily and safely.
Remember to include header to use std::reverse.
Manual reversal requires careful swapping of characters from both ends.
Strings in C++ can be reversed in place because they are mutable.
Avoid off-by-one errors when manually reversing strings.