loop through char in string c++
To loop through each character in a string in C++, you can use a for
loop in conjunction with the size()
member function of the string class. Here is an example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
for (int i = 0; i < str.size(); i++) {
char c = str[i];
std::cout << c << std::endl;
}
return 0;
}
In this example, we include the necessary headers iostream
and string
to work with strings in C++. We then declare a string variable str
and initialize it with the value "Hello, World!".
Next, we use a for
loop to iterate through each character in the string. The loop starts with an initialization statement int i = 0
which initializes the loop counter i
to 0. The loop condition i < str.size()
checks if the loop counter i
is less than the size of the string str
. The size()
member function returns the number of characters in the string.
Inside the loop, we access each character using the index operator []
and assign it to a variable c
of type char
. We then print the character c
using std::cout
and std::endl
to output a newline after each character.
Finally, we return 0 to indicate successful execution of the program.
When you run this program, it will output each character of the string on a new line, resulting in the following output:
H
e
l
l
o
,
W
o
r
l
d
!
This demonstrates how to loop through each character in a string in C++.