Loop through characters of a string backwards in C++

In this post, we will see how to loop through characters of a string in backwards direction in C++.

 

1. Naive

The naive solution is to loop through the characters of a std::string backwards using a simple for-loop and for every index, print the corresponding character using the [] operator.

 

Download   Run Code

 

2. Using Iterators

The standard way to loop through the characters of a std::string backwards is by using reverse iterators as shown below. Since the iteration is read-only, we have used the std::string::const_iterator returned by std::string::crbegin and std::string::crend.

 

Download   Run Code

 

3. Using std::for_each

We can remove the complexity of iterators by using STL algorithm std::for_each, which applies a specified function to every element in the range defined by the input iterators. Since we’re iterating backwards, we need to pass the reverse iterators.

 

Download   Run Code

Output:

yrarbil LTS

 

With introduction of lambda expressions in C++11, we can replace the function call by lambda which is a convenient way of defining an inline, anonymous functor.

 

Download   Run Code

 

4. Overloading operator<<

Finally, we can also overload the operator<< for std::string objects for the output stream as shown below.

 

Download   Run Code

Output:

yrarbil LTS

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz