insert()与substr()函数

insert()函数与substr()函数

insert()函数:

insert ( pos, str2);——将字符串str2插入到原字符串下标为pos的字符前

insert (pos, n, c);——在将n个字符c插入到原字符串下标为pos的字符前

insert (pos, str2, pos1, n);——将st2r从下标为pos1开始数的n个字符插在原串下标为pos的字符前

语法:str1.insert(pos , str2); 等等

代码参考

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

int main()
{   
    //insert()函数
    string str1 = "abef";
    string s1 = "cd";
    str1.insert(2,s1);
    cout<<str1<<endl;//abcdef 在串str下标为2的e前插入字符串str2
    
    str1.insert(2,5,'c');
    cout<<str1<<endl;//abccccccdef 在串str1下标为2的e前插入5个字符'c'
    
    string str2="hello";
    string s2="weakhaha";
    str2.insert(0,s2,1,3);//将字符串s2从下标为1的e开始数3个字符,分别是eak,插入原串的下标为0的字符h前
    cout<<str2<<endl;

	return 0;
}

substr()函数

主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。如果没有指定长度_Count或_Count+_Off超出了源字符串的长度,则子字符串将延续到源字符串的结尾也可以用于字符的插入拼接

语法:substr(size_type _Off = 0,size_type _Count = n)

​ substr(pos, n)

解释:pos - 从此位置开始拷贝

​ n - 拷贝长度为 n 的字符串(注意:n 是长度而不是下标)

代码参考:

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

int main()
{   
    string str1 = "abcg";
    string str2 = "def";
    
// string类字符串可以直接进行连接
//从a开始 长度为3:(下标)+1 的字符串abc + def + g
    string str3 = str1.substr(0,2+1) + str2 + str1.substr(2+1);
//                    子串                            子串
    cout<<str3<<endl;//abcdefg

	return 0;
}

总结:

在前插入为insert,复制字串用strsub。两者均可用来实现字符串的插入操作

posted @ 2021-08-11 15:18  时间最考验人  阅读(245)  评论(0编辑  收藏  举报