Reverse a string in-place in C++
This post provides an overview of some of the available alternatives to reverse a string in-place in C++ using simple for-loop, iterators, and std::reverse
algorithm.
1. Using simple for-loop
A simple solution is to loop through the first half of the given string using a simple for-loop and swap the current character with the corresponding character on the other half of the string using STL’s std::swap
algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> #include <algorithm> using namespace std; // Function to reverse a string in-place in C++ void reverse(string &s) { int n = s.length(); for (int i = 0; i < n/2; i++) { std::swap(s[i], s[n-i-1]); } } int main() { std::string s("Reverse a string in C++"); reverse(s); cout << s; return 0; } |
2. Using Iterators
We can avoid iterating with indices with the help of iterators. The reverse algorithm can be implemented as follows using iterators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <string> #include <algorithm> using namespace std; // Function to reverse a string in-place in C++ void reverse(string &s) { int n = s.length(); std::string::iterator start = s.begin(); std::string::iterator end = s.end(); while (std::distance(start, end) > 0) { std::swap(*(start++), *(--end)); } } int main() { std::string s("Reverse a string in C++"); reverse(s); cout << s; return 0; } |
3. Using std::reverse
function
Finally, the recommended option is to use the standard algorithm std::reverse
from the C++ Standard Library, which can in-place reverse a range of a string or the whole string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <algorithm> using namespace std; // Function to reverse a string in-place in C++ void reverse(string &s) { reverse(s.begin(), s.end()); } int main() { std::string s("Reverse a string in C++"); reverse(s); cout << s; return 0; } |
That’s all about reversing a string in-place in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)