我是靠谱客的博主 无聊彩虹,这篇文章主要介绍【C++】字符串遍历的三种方式,现在分享给大家,希望可以做个参考。

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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)使用迭代器遍历——类似于容器的使用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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

最后

以上就是无聊彩虹最近收集整理的关于【C++】字符串遍历的三种方式的全部内容,更多相关【C++】字符串遍历内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部