C++【string类的使用】(下)

上一篇文章:C++【string类的使用】(上)

1. string类获取元素

1.1 operator[] (重点) 和 at

在这里插入图片描述
他们两个的功能几乎一样,都是返回string中一个字符的引用
在这里插入图片描述

Returns a reference to the character at position pos in the string.
返回string中第pos位置的引用

在这里插入图片描述

Returns a reference to the character at position pos in the string.
返回string中第pos位置的引用


The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not.
函数会自动检查 pos 是否是字符串中字符的有效位置(即 pos 是否小于字符串长度),如果不是,则抛出 out_of_range 异常。

这是atoperator[]不同的点,operator[]是用assert进行检查下标,当下标不合法直接报错,at是抛异常

	string s1("hello world");
	//operator[]  返回的是引用
	cout << s1[1] << endl;
	s1[1] = 'x';
	cout << s1 << endl;

在这里插入图片描述

	string s1("hello world");
	try
	{
   
		//at 和 operator[]的功能一样
		cout << s1.at(1) << endl;
		s1.at(-1) = 'e';
		cout << s1 << endl;
	}
	catch (const exception& e)
	{
   
		cout << e.what() << endl;
	}

在这里插入图片描述
但是他们的功能上是完全相同的

	string s1("hello world");
	try
	{
   
		//at 和 operator[]的功能一样
		cout << "at:" << s1.at(1) << endl;
		s1.at(1) = 'e';
		cout << "at:" << s1 << endl;
	}
	catch (const exception& e)
	{
   
		cout << e.what() << endl;
	}

	//operator[]  返回的是引用
	cout <<"operaor[]:" << s1[1] << endl;
	s1[1] = 'x';
	cout << "operaor[]:" << s1 << endl;

在这里插入图片描述

1.2 front 和 back

在这里插入图片描述
返回第一个和最后一个字符的引用
在这里插入图片描述

Returns a reference to the first character of the string.
返回字符串中第一个字符的引用


Unlike member string::begin, which returns an iterator to this same character, this function returns a direct reference.
不像成员变量string::begin()一样,返回指向同一字符的迭代器,front函数直接返回第引用


This function shall not be called on empty strings.
这个函数不能在空字符串上使用

在这里插入图片描述

Returns a reference to the last character of the string.
返回string中最后一个字符的引用


This function shall not be called on empty strings.
这个函数不能在空字符串上使用

	string s1("hello world");

	//back --> 返回最后一个有效字符的引用
	cout << s1.back() << endl;

	//front --> 返回第一个有效字符的引用
	cout << s1.front() << endl;

在这里插入图片描述

2. string类对象的修改操作

2.1 push_back

push_back我们很熟悉了,就是在在字符串后尾插字符c
在这里插入图片描述

Appends character c to the end of the string, increasing its length by one.
添加一个字符在string的末尾,string的size增加一

	string s1("hello world");
	string s2("0123456789abcd");
	//push_back(尾插)
	s1.push_back('x');
	cout << s1 << endl;
	//只能一个字符一个字符的插入
	//s1.push_back("abc");

在这里插入图片描述
只能一个字符一个字符的插入,插入字符串会报错
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值