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
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
.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With