温馨提示×

c++遍历字符串的方法是什么

小亿
140
2023-06-28 15:49:38
栏目: 编程语言

在C++中,有几种方法可以遍历字符串:

  1. 使用for循环:可以使用for循环来遍历字符串的每个字符。使用字符串的长度作为循环的终止条件,并使用下标访问每个字符。
std::string str = "Hello World";
for(int i = 0; i < str.length(); i++) {
char c = str[i];
// 对字符c进行操作
}
  1. 使用迭代器:字符串类std::string提供了begin()和end()方法,可以返回指向字符串首字符和末字符的迭代器。可以使用迭代器来遍历字符串的每个字符。
std::string str = "Hello World";
for(auto it = str.begin(); it != str.end(); ++it) {
char c = *it;
// 对字符c进行操作
}
  1. 使用范围for循环:C++11引入了范围for循环,可以更简洁地遍历字符串的每个字符。
std::string str = "Hello World";
for(char c : str) {
// 对字符c进行操作
}

无论使用哪种方法,都可以遍历字符串的每个字符,并对其进行相应的操作。

0