C++标准库中的string容器是一个非常实用的字符序列,它可以用于存储和操作字符串。
1:string的构造函数
void test01(){
string s1;//默认构造
const char*str="hello world";
string s2(str);
string s3(s2);
string s4(11,'b');//创建11个b
cout<<s2<<endl;
cout<<s3<<endl;
cout<<s4;
}//string构造函数
2:string赋值
void test02(){
string str1;
str1="hello world";
cout<<str1<<endl;
string str2;
str2=str1;
cout<<str2<<endl;
string str3;
str3='a';
cout<<str3<<endl;
string str4;
str4.assign("hello C++");
cout<<str4<<endl;
string str5;
str5.assign("hello C++",5);
cout<<str5<<endl;
string str6;
str6.assign(str5);
cout<<str6<<endl;
string str7;
str7.assign(7,'v');
cout<<str7<<endl;
}//string赋值
3:字符串拼接
void test03(){
string s1="my";
s1+="apple";
cout<<s1<<endl;
string s2="my";
s2+='s';
cout<<s2<<endl;
string s3="my";
s3+=s1;
cout<<s3<<endl;
string s4="I";
s4.append("love");
cout<<s4<<endl;
s4.append("game1234",4);
cout<<s4<<endl;
// s4.append(s3);
// cout<<s4<<endl;
s4.append(s3,0,2);//只截取s3从0开始2个字符
cout<<s4<<endl;
}//字符串拼接
4:字符串查找
void test04(){
string s1="abcdefgde";
int pos=s1.find("de");
if(pos==-1){
cout<<"no"<<endl;
}
else{
cout<<pos<<endl;//返回d第一次出新的位置
}
int ppos=s1.rfind("de");
cout<<ppos<<endl;//rfind是从右往左查找,find是从左往右查找
}//字符串的查找
5:字符串的替换
void test05(){
string str1="abcdefg";
str1.replace(1,3,"1111");//从1个位置起3个字符被替换为"1111"
cout<<str1<<endl;
}//字符串的替换
6:字符串的比较
void test06(){
string s1="my";
string s2="my";
if(s1.compare(s2)==0){
cout<<"yes";
}//比较两个字符串
}//字符串的比较
7:字符串的存取和修改
void test07(){
string str="hello";
//存取
for(int i=0;i<str.size();i++){
//cout<<str[i];//通过[]访问
cout<<str.at(i)<<" ";//通过at访问;
}
//修改
str[2]='p';
str.at(1)='x';
cout<<str<<endl;
}//字符存取和修改
8:字符串插入和修改
void test08(){
string str="hello";
//插入
str.insert(1,"my");//在第一个位置插入my
cout<<str<<endl;
//删除
str.erase(1,3);
cout<<str<<endl;//在第一个位置删除3个字符
}//string插入删除
9:string求子串
void test09(){
string str="hello";
string sub=str.substr(1,3);//从第一个位置截取3个字符
cout<<sub<<endl;
string email="gaogao@qq.com";
int pos=email.find('@');//6
string sub1=email.substr(0,pos);//6
cout<<sub1<<endl;
}//string 求子串