In this article, we are going to learn how to iterate through the string in C++?
There are many ways to iterate over characters of a string in C++. To learn the ways, read the following article which is defining all the methods ahead.
title: "How to iterate through string in C++?"
tags: cpp
canonical_url: https://kodlogs.com/blog/338/how-to-iterate-through-string-in-c
Methods
Using functions
In this method, we will be using a loop to iterate over characters of a string.
void print(const std::string &s)
{
for (std::string::size_type i = 0; i < s.size(); i++) {
std::cout << s[i] << ' ';
}
}
Using range-based loops
The method given ahead is the recommended approach in C++11 and we will be iterating over characters of a string by using range-based for loop.
void print(const std::string &s)
{
for (char const &c: s) {
std::cout << c << ' ';
}
}
Using predefined iterators
C++ has iterators for iterating characters. So we can also iterate using iterators in C++. Iteration is read-only, so we can use iterators.
void print(const std::string &s)
{
for (auto it = s.cbegin() ; it != s.cend(); ++it) {
std::cout << *it << ' ';
}
}
Using algorithms
There is an algorithm STL algorithm, which tries a specified function to each element for the input range. This helps in reducing the complication.
#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;
}
By overloading
You can also overload the function for iterating the characters.
#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;
}
Finally, if you have any doubts you can ask in the comment section, I will try my best, usually, no one does. #peace
Top comments (0)