如何在 C++ 中对字符串中的每个字符执行 for 循环?
最佳答案
循环通过 characters
std::string
,使用基于范围的 for 循环(它来自 C++11,已在 GCC、clang 和 VC11 beta 的最新版本中得到支持):std::string str = ???; for(char& c : str) { do_things_with(c); }
使用迭代器循环遍历
std::string
的字符:std::string str = ???; for(std::string::iterator it = str.begin(); it != str.end(); ++it) { do_things_with(*it); }
使用老式 for 循环遍历
std::string
的字符:std::string str = ???; for(std::string::size_type i = 0; i < str.size(); ++i) { do_things_with(str[i]); }
循环遍历以空字符结尾的字符数组的字符:
char* str = ???; for(char* it = str; *it; ++it) { do_things_with(*it); }
关于c++ - 对于字符串中的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9438209/