C++——遍历string的三种方式

本次博客,我将记录遍历string的三种方式

1.for循环下标遍历:

	//.size()
	string str="abcdefg";
	for(int i=0;i<str.size();i++){
		cout<<str[i]<<' ';
	}
	
	//.length()
	string str="abcdefg";
	for(int i=0;i<str.length();i++){
		cout<<str[i]<<' ';
	}

2.使用迭代器访问string:

	string str="abcdefg";
	auto it=str.begin();
	for(;it!=str.end();it++){
		cout<<*it<<' ';
	}

3.新式for循环

	string str="abcdefg";
	for(auto ch:str){
		cout<<ch<<' ';
	}

三种遍历方式执行结果均为:
a b c d e f g


本文完

posted @ 2022-07-26 11:59  Sky6634  阅读(4069)  评论(0)    收藏  举报