Quester
Quester

Reputation: 2009

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

Thank you

Upvotes: 8

Views: 6583

Answers (3)

Ali Kazmi
Ali Kazmi

Reputation: 1458

use range based for loop like this

char a1[5] = {'a', 'a', 'a', 'c'};
for (auto a : a1)
    cout << a << endl;

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254631

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.

Upvotes: 24

Marco A.
Marco A.

Reputation: 43662

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"

Upvotes: 13

Related Questions