Loop through characters of a string backward in C++
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.
|
1 2 3 4 5 6 |
void print(std::string const &s) { for (int i = s.size() - 1; i >= 0; i--) { std::cout << s[i]; } } |
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.
|
1 2 3 4 5 6 |
void print(std::string const &s) { for (auto it = s.crbegin() ; it != s.crend(); ++it) { std::cout << *it; } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <algorithm> void fn(char const &c) { std::cout << c; } void print(std::string const &s) { std::for_each(s.rbegin(), s.rend(), fn); } int main() { std::string s("STL library"); print(s); return 0; } |
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.
|
1 2 3 4 5 6 |
void print(std::string const &s) { std::for_each(s.rbegin(), s.rend(), [] (char const &c) { std::cout << c; }); } |
4. Overloading operator<<
Finally, we can also overload the operator<< for std::string objects for the output stream, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <iterator> std::ostream& operator<< (std::ostream &os, const std::string &s) { for (int i = s.size() - 1; i >= 0; i--) { std::cout << s[i]; } return os; } int main() { std::string s("STL library"); std::cout << s; return 0; } |
Output:
yrarbil LTS
That's all about looping through characters of a string backward in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)