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.

Download  Run Code

2. Using Iterators

We can avoid iterating with indices with the help of iterators. The reverse algorithm can be implemented as follows using iterators:

Download  Run Code

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.

Download  Run Code

That’s all about reversing a string in-place in C++.