关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

【C++】字符串遍历的三种方式

发布时间:2023-06-26 14:00:20

(1)常规遍历——利用字符串的长度进行遍历

#include#includeusing namespace std;  void Traverse(string str) {  for (size_t i = 0; i < str.size(); i++)  {  cout << str[i] ;  }  cout << endl; }  int main() {  Traverse("abcde");   system("pause");  return 0; }   输出结果:abcde

   


(2)使用迭代器遍历——类似于容器的使用

#include#includeusing namespace std;  void Traverse(string str) {  //迭代器--在STL中,不破坏封装的情况下去访问容器  string::iterator it = str.begin();  while (it != str.end())  {  cout << *it;  it++;  }  cout << endl; }  int main() {  Traverse("abcde");   system("pause");  return 0; }   输出结果:abcde

   


(3)利用 for 循环,较新颖——此方法来源c++11

#include#includeusing namespace std;  void Traverse(string str) {  for (auto ch : str) //ch依次取的是str里面的字符,直到取完为止  {  cout << ch;  }  cout << endl; }  int main() {  Traverse("abcde");   system("pause");  return 0; }   输出结果:abcde

   



/template/Home/leiyu/PC/Static