1. 常规方式
复制代码
1
2
3
4string s="hello" for(int i=0;i<s.size();i++){ cout<<s[i]<<""; }
2.迭代器方式
begin接口 : iterator begin();
end 接口: iterator end();
循环方法
复制代码
1
2
3
4
5
6string s = "hello"; string::iterator it = s.begin(); while (it != s.end()) { cout << *it << ""; ++it; }
3. 新for循环(C++11)
1.只读: for(const auto& 变量: 需要遍历的容器)
2.可读可写: for(auto &变量: 需要遍历的容器)
复制代码
1
2
3
4
5
6
7
8string s = "hello"; for (const auto& ch : s) { cout << c << "";//只读 } for (auto& c : s) { c = 'a';// 可读可写 }
最后
以上就是彪壮外套最近收集整理的关于C++遍历字符串的全部内容,更多相关C++遍历字符串内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复