片头
嗨喽~ 我们又见面啦,在上一篇C++之String类(上)中,我们对string类的函数有了一个初步的认识,这一篇中,我们将继续学习string类的相关知识。准备好了吗?咱们开始咯~
二、标准库中的string类
2.5 string类对象的修改操作
函数名称 | 功能说明 |
push back | 在字符串后尾插字符c |
append | 在字符串后追加一个字符串 |
operator+= | 在字符串后追加字符串str |
assign | 给字符串原有的内容进行覆盖,类似于赋值 |
insert | 用于在字符串的pos位置插入一个字符串、字符串的前n个字符或n个字符c |
erase | 用于在字符串的pos位置删除len个字符 |
replace | 替换源字符串中的字符 |
c str | 返回c格式字符串 |
rfind + npos | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
find | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
substr | 在str中从pos位置开始,截取n个字符,然后将其返回 |
swap | 用于交换2个string类对象 |
operator+ | 返回一个新构造的string类对象,其值是lhs和rhs的合并 |
getline | 用于字符串的输入 |
(1)push back函数
我们测试一下:
void test_string15() {
string s1("hello world");
cout << s1 << endl;
//在s1字符串的后面尾插'x'
s1.push_back('x');
cout << s1 << endl;
}
(2)append函数
我们测试一下:
void test_string16() {
string s1("hello world");
cout << s1 << endl;
//在s1字符串的后面追加一个字符串
s1.append(" yyyyyy!!!!");
cout << s1 << endl;
}
(3)此外,我们还可以使用运算符operator+=函数重载
代码如下:
void test_string17() {
string s1("hello world");
cout << s1 << endl;
string s2("111111");
//在s1字符串的后面追加一个字符串
s1 += 'y';
s1 += "zzzzzzzzzzz";
s1 += s2;
cout << s1 << endl;
}
注意:
①在string尾部追加字符时,s.push_back(c)/s.append(1,c)/s += 'c' 三种的实现方式差不多,一般情况下,string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串
②对string操作时,如果能够大概预估到放多少字符,可以先通过reverse把空间预留好
(4)assign函数
assign函数类似于给字符串原有的内容进行覆盖,类似于赋值
void test_string18() {
string s1("hello world");
cout << s1 << endl;
s1.assign("11111");
cout << s1 << endl;
}
(5)insert函数
①在s1字符串前头插"xxxxx"
void test_string19() {
string s1("hello world");
cout << s1 << endl;
//在s1字符串前头插"xxxxx"
s1.insert(0, "xxxxx");
cout << s1 << endl;
}
②在s1字符串前头插一个字符'y'
void test_string20() {
string s1("hello world");
cout << s1 << endl;
//在s1字符串前头插单个字符'y'
s1.insert(0, 1,'y');
cout << s1 << endl;
}
③使用迭代器,在s1字符串钱头插单个字符'y'
void test_string21() {
string s1("hello world");
cout << s1 << endl;
//在s1字符串前头插单个字符'y'
s1.insert(s1.begin(), 'y');
cout << s1 << endl;
}
④在s1字符串前插入s2字符串,二者都采用迭代器的形式
void test_string22() {
string s1("hello world");
cout << s1 << endl;
string s2("11111");
//在s1字符串前头插s2字符串
s1.insert(s1.begin(),s2.begin(),s2.end());
cout << s1 << endl;
}
(6)erase函数
①当pos=0,len=1,说明,从下标为0的元素开始,删除1个字符</