Quick Q: In Python I write "for char in str" -- what do I write in C++? -- StackOverflow

Quick A: for( char c : str ).

Recently on StackOverflow:

Traversing a string in C++

I am looking for something similar to traversing a string in Python:

i.e.

for char in str:
    do something

How can I do this in C++?

Add a Comment

Comments are closed.

Comments (3)

1 0

Hello Kitty said on Nov 2, 2014 11:41 AM:

for(unsigned int i = 0; i < str.length(); i++)
{
cout << str[i];
dostuff
}


With constant iterator preventing changing the string
for(auto i = str.cbegin(); i != str.cend(); i++)
{
cout << *i;
dostuff
}


With nonconstant iterator allowing you to change the string.
for(auto i = str.begin(); i != str.end(); i++)
{
cout << *i;
dostuff
}


You could also use foreach and a lambda expression too. Look that up if interested.

0 0

Arek Bal said on Nov 2, 2014 01:46 PM:


std::string s = "hello world";

for (auto c : s)
{
}
//or... in case u need to modify given chars
for (auto& c : s)
c = c + 1; // or whatever
0 0

Bayu Setiaji said on Nov 17, 2014 03:50 PM:

I usually use the following:

for(char& c:str)
// use c, without modifying given char