上一篇文章: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 异常。
这是at
和operator[]
不同的点,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");
只能一个字符一个字符的插入,插入字符串会报错