(1)常规遍历——利用字符串的长度进行遍历
#include <iostream> #include <string> using 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 <iostream> #include <string> using 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 <iostream> #include <string> using 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