chevron_left
0 points
15 11 8




 

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.

Methods

 

  1. 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] << ' ';
	}
}

 

  1. 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 << ' ';
	}
}

 

  1. 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 << ' ';
	}
}

 

  1. 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;
}

 

  1. 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

More Posts

How to iterate through a set in C++? Lalit Kumar - Aug 9, 2020
How to iterate through a map in C++? Lalit Kumar - May 14, 2020
How to loop through characters in a string java amna - Jul 2
Iterate over a string in java usmanhashmi - Aug 11
What does break do in c++? Lalit Kumar - Nov 27, 2020
how to check if a file exists in C++? Lalit Kumar - May 6, 2020
How to check if an array is empty C++? Lalit Kumar - May 1, 2020
How to pass an array to a function C++? Lalit Kumar - Apr 29, 2020
C program to replace a word in a string without using function Sanjana Sagar - May 20
Pass an 2D array to a function in C++ Lalit Kumar - Sep 15, 2020