string函数迭代器的使用

string函数迭代器的使用

迭代器的声明:

string str("abcdefg");

//正向遍历str
std::string iterator it = str.begin();	//或end()
std::string const_iterator it = str.begin();	//或cend(),只读

//反向遍历str
std::string reverse_iterator r_it = str.rbegin();	//或rend()
std::string const_reverse_iterator cr_it = str.crbegin();	//或crend(),只读

在C++11中,支持auto语法,由编译器自动推测变量的类型,减少书写的麻烦

auto it = str.begin();

举例:

/*
>Plan:string的迭代器
>Author:ADiiana
>Time:2019/03/17
*/

#include<iostream>
#include<string>
using namespace std;

int main(){

	string str("abcdefg");

	cout << "正向遍历: ";
	for (string::iterator it = str.begin(); it != str.end(); ++it){
		cout << *it;
	}
	cout << endl;

	//定义反向遍历迭代器
	cout << "反向遍历: ";
	for (string::reverse_iterator it = str.rbegin(); it != str.rend(); ++it)
		cout << *it;
	cout << endl;

	//定义非const可以用迭代器改变string的值。
	cout << "输出字符串大写,正向遍历: ";
	for (string::iterator it = str.begin(); it != str.end(); ++it){
		*it = *it - 'a' + 'A';
		cout << *it;
	}
	cout << endl;
	
	/*	//编译报错: 不能给常量赋值

	cout << "输出字符串大写,正向遍历: ";
	for (string::const_iterator it = str.begin(); it != str.end(); ++it){
		*it = *it - 'a' + 'A';
		cout << *it;
	}
	cout << endl;

	*/
	system("pause");
	return 0;
}

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值