string容器
初始化
string str1="hello world";
string str2("hello world");
string str3(str2);
string str4(4,'n');//str4是由4个n组成
string str5='x';
赋值
与初始化很相似。
string str1="hello world";
string str2(str1);//
string str3.assign("hello world");
string str4.assign("hello world",5)//将hello world的前五个字符对str4赋值
string str5.assign(str4);
拼接
//第一种
string str1="我喜欢";
string str2="打篮球!";
str1+=str2;
cout<<str1<<endl;//即 我喜欢打篮球!
//第二种
string str3="I ";
str3.append("love you");//append
cout<<str3<<endl;//即 I love you
//第三种
string str4="i love ";
str4.append("game abcd",4);//取前四个
cout<<str4<<endl;//即i love game
查找和替换
//查找
//find
string str1="abcdefg";
int a=str1.find("de");//找de在字符串中的位置
cout<<a<<endl;//结果即为3
//rfind
string str2="abcdefgde";
int a=str2.rfind("de");//找位置
cout<<a<<endl;//结果即为7
//二者的区别:find从左往右, rfind从右往左,但最后显示的下标数都是从左到右
//替换
string str3="abcdef";
str3.replace(1,3,"1111");//从一号位置起三个字符即bcd替换为1111
cout<<str3<<endl;//结果即a1111ef
比较
//逐个字符进行比较
string str1="hello";
string str2="zello";
if(str1.compare(str2)<0)
{
cout<<"str1小于str2"<<endl;
}
字符存取
string str1="hello";
for(int i=0;i<str1.size();i++)
{
cout<<str1[i]<<endl;//或者使用at,即为下一行代码
cout<<str1.at(i)<<endl;
}
//修改
str1[0]='o';
cout<<str1<<endl;//或者用at的方式进行修改
插入和删除
//插入
string str="hello";
str.insert(1,"hi");
cout<<"str="<<str<<endl;//此时输出的是hhiello
//删除
str.erase(1,3);
cout<<"str="<<str<<endl;//此时输出的便是hello
string子串
在字符串中截取想要的子串
string str1="hello";
string str2=str1.substr(1,3);//从下标为1的位置截取三个
cout<<"str2="<<str2<<endl;//结果即为ell
//举例
string str3="qiqi@163.com";//截取用户信息
int m=str3.find('@');
string str4=str3.substr(0,m);
cout<<str4<<endl;//结果即为qiqi