Iterate over characters of a string in C++
This post will discuss how to iterate over the characters of a string in C++.
1. Naive Solution
The idea is to iterate over the characters of a std::string using a simple for-loop and print each character at the current index using the [] operator.
|
1 2 3 4 5 6 |
void print(const std::string &s) { for (std::string::size_type i = 0; i < s.size(); i++) { std::cout << s[i] << ' '; } } |
Output:
h e l l o
2. Using range-based for-loop
The recommended approach in C++11 and above is to iterate over the characters of a std::string using a range-based for-loop.
|
1 2 3 4 5 6 |
void print(const std::string &s) { for (char const &c: s) { std::cout << c << ' '; } } |
Output:
h e l l o
3. Using Iterators
We can also iterate over the characters of a std::string using iterators. Since the iteration is read-only, we can use std::string::const_iterator returned by std::string::cbegin and std::string::cend.
|
1 2 3 4 5 6 |
void print(const std::string &s) { for (auto it = s.cbegin() ; it != s.cend(); ++it) { std::cout << *it << ' '; } } |
Output:
h e l l o
4. Using std::for_each function
We can even reduce the complexity by using the std::for_each STL algorithm, which applies a specified function to every element of the input range.
|
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(const std::string &s) { std::for_each(s.begin(), s.end(), fn); } int main() { std::string s("hello"); print(s); return 0; } |
Output:
h e l l o
We can even replace the function call with lambda expressions in C++11. A lambda is a convenient way of defining an inline, anonymous functor at the location, where it is passed as an argument to some function.
|
1 2 3 4 5 6 |
void print(const std::string &s) { std::for_each(s.begin(), s.end(), [] (char const &c) { std::cout << c << ' '; }); } |
Output:
h e l l o
5. Overloading operator<<
Finally, we can also overload the operator<< for std::string objects, 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 (char const &c: s) { os << c << ' '; } return os; } int main() { std::string s("hello"); std::cout << s; return 0; } |
Output:
h e l l o
That's all about iterating over characters of a string 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 :)