c++的string有两种赋值方式
//两种赋值方式
string str1="string1";
string str2("string2");
cout<<str1<<" "<<str2<<endl;
输出
子字符串的查找
方法一:调用find方法
//子字符串的查找
string strall="abcdefgbcd";
string strzi("bc") ;
//返回第一次出现索引 没有返回-1
int i=strall.find("defg");
//从后往前找
int j=strall.rfind("bd");
cout<<i<<" "<<j<<endl;
输出:
方法二:调用函数strstr()
第一个参数为主字符串指针,第二个为子字符串指针 ,返回首次出现的地址,不是子字符串返回NULL
char a[]="nihao";
char b[]="hao";
char *p=strstr(a,b);
if(p!=NULL){
int m=p-a;
cout<<m<<endl;
}
截取字符串
截取字符串 substr(size_t pos=0,size_t len=npos),第一个参数为截取的位置,第二个参数为截取的长度 ,原字符串不改变
string cut1=strall.substr(2);
string cut2=strall.substr(2,4);
//超过了字符串的长度仍会输出
string cut3=strall.substr(2,6);
cout<<cut1<<" "<<cut2<<" "<<cut3<<" "<<strall<<endl;
输出:
字符串插入
改变了原有字符串 ,第一个参数要插入的位置,第二个参数要插入的字符串
string s1="helld";
string s2="o worl";
s1.insert(4,s2);
cout<<s1<<endl;
输出:
第三个参数为s4的起始位置,第四个参数为结束位置 左开右闭
string s3="China";
string s4="gggood";
s3.insert(5,s4,2,6);
cout<<s3<<endl;
在第一个参数位置之前插入第二个参数个数的第三个参数字符
string s5="gd";
char ch='o';
s5.insert(1,2,ch);
cout<<s5<<endl;
删除字符串
删除参数后的所有字符(包括参数所在位置)
string s6="abcdefg";
s6.erase(3);
cout<<s6<<endl;
删除参数位置后n个字符
string s7="abcd";
s7.erase(2,1);
cout<<s7<<endl;