Reverse a string in C++

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


 

1. Using simple for-loop

The simple solution is to loop through the characters of the given string backwards using a simple for-loop and append the corresponding character at each index to a new string using the string::append method.

 

Download   Run Code

 

2. Using Iterators

The standard way to loop through the characters of a string backwards is by using reverse iterators. Since iteration is read-only, it is recommended to use const reverse iterators returned by std::string::crbegin and std::string::crend. The std::string::crbegin points to the last character of the string, and std::string::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

 

3. Using std::for_each

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 backwards 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

 

4. std::string constructor

We can even use range constructor of std::string to reverse a string. The idea is to pass the range defined by the reverse iterators std::string::rbegin and std::string::rend to the string constructor.

 

Download   Run Code

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Categories

Leave a Reply

avatar
  Subscribe  
Notify of