+ 1

How can i check characters of a string one by one in C++ ?

16th Aug 2017, 5:03 PM
Rohan Singh Aswal
Rohan Singh Aswal - avatar
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 }
16th Aug 2017, 5:15 PM
Schindlabua
Schindlabua - avatar
+ 2
Use auto& instead though. or const auto& if you don't plan to modify the characters. Otherwise you're just making unnecessary copies.
16th Aug 2017, 5:29 PM
Dennis
Dennis - avatar
+ 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
16th Aug 2017, 8:01 PM
aklex
aklex - avatar
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.
16th Aug 2017, 9:15 PM
Dennis
Dennis - avatar