For every character in string
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); }
A for loop can be implemented like this:
string str("HELLO");
for (int i = 0; i < str.size(); i++){
cout << str[i];
}
This will print the string character by character. str[i]
returns character at index i
.
If it is a character array:
char str[6] = "hello";
for (int i = 0; str[i] != '\0'; i++){
cout << str[i];
}
Basically above two are two type of strings supported by c++. The second is called c string and the first is called std string or(c++ string).I would suggest use c++ string,much Easy to handle.
In modern C++:
std::string s("Hello world");
for (char & c : s)
{
std::cout << "One character: " << c << "\n";
c = '*';
}
In C++98/03:
for (std::string::iterator it = s.begin(), end = s.end(); it != end; ++it)
{
std::cout << "One character: " << *it << "\n";
*it = '*';
}
For read-only iteration, you can use std::string::const_iterator
in C++98, and for (char const & c : s)
or just for (char c : s)
in C++11.