(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
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者