This post will discuss how to loop through characters of a string in backward direction in C++.

1. Naive Solution

A naive solution is to loop through the characters of a std::string backward 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 backward 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 function

We can remove the complexity of iterators by using the 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 backward, we need to pass the reverse iterators.

Download  Run Code

Output:

yrarbil LTS

 
With the introduction of lambda expressions in C++11, we can replace the function call with 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

That's all about looping through characters of a string backward in C++.