For every character in string

Jack Wilsdon picture Jack Wilsdon · Feb 24, 2012 · Viewed 432.4k times · Source

How would I do a for loop on every character in string in C++?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Feb 24, 2012
  1. 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);
    }
    
  2. 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);
    }
    
  3. 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]);
    }
    
  4. Looping through the characters of a null-terminated character array:

    char* str = ???;
    for(char* it = str; *it; ++it) {
        do_things_with(*it);
    }