This post provides an overview of some of the available alternatives to reverse a string in C++ without modifying the original string.

1. Using the std::reverse algorithm

The standard way to reverse a string in C++ is to use the std::reverse algorithm from the <algorithm> header. This algorithm reverses the order of the elements in a range, such as a string or an array. The reverse algorithm is very powerful and flexible, as it can work with different types of containers and iterators. To use the reverse algorithm to reverse a string in C++, we need to provide two arguments: the beginning and the end of the range. For example:

Download  Run Code

 
Note that the reverse algorithm is simple to use, but modifies the original string in-place, which means that it changes the order of the characters in the original string.

2. Using std::string::rbegin and std::string::rend functions

Another way to reverse a string in C++ is to use the rbegin and rend functions from the std::string class. These functions return reverse iterators that point to the last and the first element of the string, respectively. Reverse iterators are special types of iterators that move backwards instead of forwards when incremented or decremented. To use the rbegin and rend functions to reverse a string in C++, we need to create a new string object and initialize it with the reverse iterators of the original string. For example:

Download  Run Code

3. Using std::string::crbegin and std::string::crend functions

Another option is to loop through the characters of a string backward is by using reverse iterators. Since iteration is read-only, it is recommended to use const reverse iterators returned by crbegin and crend. The crbegin points to the last character of the string, and crend points to the first character of the string. Note that in a reverse iterator, the operator++ moves the iterator by one position to the previous character.

Download  Run Code

4. Using std::for_each function

We can remove the complexity of iterators with the standard STL algorithm std::for_each, which applies a specified condition to every element in the range defined by the input iterators. Since we’re iterating backward and the iteration is read-only, it is recommended to use const reverse iterators returned by std::string::crbegin and std::string::crend.

Download  Run Code

5. Using simple for-loop

Finally, we can loop through the characters of the given string backward using a simple for-loop and append the corresponding character at each index to a new string using the string::append function. For example:

Download  Run Code

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