Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a string in C++

Tags:

c++

c++11

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++?

Thank you

like image 219
Quester Avatar asked Oct 29 '14 11:10

Quester


2 Answers

if str is std::string, or some other standard container of char, then that's

for (char c : str) {
    // do something
}

If you want to modify the characters of the string, then you'll want a reference char & c rather than a value char c.

like image 142
Mike Seymour Avatar answered Nov 01 '22 11:11

Mike Seymour


With a std::string it's going to be quite easy:

std::string myStr = "Hello";
for (char c : myStr)
    std::cout << c; // Print out every character

or by reference in case you want to modify it..

std::string myStr = "Hello";
for (char& c : myStr)
    c = 'A';
// mystr = "AAAAA"
like image 27
Marco A. Avatar answered Nov 01 '22 13:11

Marco A.