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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

Output:

h e l l o

5. Overloading operator<<

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

Download  Run Code

Output:

h e l l o

That's all about iterating over characters of a string in C++.