阅读量:77
在C++中,遍历字符串可以使用以下几种技巧:
- 使用for循环遍历字符串的每个字符:
std::string str = "hello";
for (int i = 0; i < str class="hljs-built_in">length(); i++) {
char c = str[i];
// 这里对字符c进行操作
}
- 使用范围for循环遍历字符串的每个字符:
std::string str = "hello";
for (char c : str) {
// 这里对字符c进行操作
}
- 使用迭代器遍历字符串的每个字符:
std::string str = "hello";
for (std::string::iterator it = str.begin(); it != str.end(); it++) {
char c = *it;
// 这里对字符c进行操作
}
无论使用哪种方法,都可以对字符串中的每个字符进行遍历操作。根据具体需求选择最适合的方法来遍历字符串。