How would I do a for loop on every character in string in C++?
Looping through the characters of a std::string
, using a range-based for loop (it's from C++11, already supported in recent releases of GCC, clang, and the VC11 beta):
std::string str = ???;
for(char& c : str) {
do_things_with(c);
}
Looping through the characters of a std::string
with iterators:
std::string str = ???;
for(std::string::iterator it = str.begin(); it != str.end(); ++it) {
do_things_with(*it);
}
Looping through the characters of a std::string
with an old-fashioned for-loop:
std::string str = ???;
for(std::string::size_type i = 0; i < str.size(); ++i) {
do_things_with(str[i]);
}
Looping through the characters of a null-terminated character array:
char* str = ???;
for(char* it = str; *it; ++it) {
do_things_with(*it);
}