+ 1
How can i check characters of a string one by one in C++ ?
4 Answers
+ 4
If you are on C++11 or later:
std::string mystring = "Hello this is a test!";
for(auto c : mystring){
std::cout << c << std::endl; // Will print out each letter on a new line
}
+ 2
Use auto& instead though.
or const auto& if you don't plan to modify the characters.
Otherwise you're just making unnecessary copies.
+ 1
@Dennis for chars it hardly makes a difference. You lose the advantage of not making a copy anyways, because now you will have extra instructions due to the referencing
0
@aklex
Well
https://stackoverflow.com/questions/15927033/what-is-the-correct-way-of-using-c11s-range-based-for
told me it was better to use const auto&, so I just assumed it was better most of the time.
I did a test and the runtime with and without & were almost identical.
So I'll rather use it with & for consistency.