看代码吧!
#include<iostream>
using namespace std;
int main() {
//string是一个类
//string容器赋值操作 =
cout << "string容器赋值操作" << endl ;
string str1;
str1 = "hellow CSDN";
cout << str1<<endl;
//将字符串前几个字符赋给另一个字符串
string str2;
str2.assign("hellow CSDN", 7);
cout << str2 << endl;//hellow
str2.assign(str1, 7);
cout << str2 << endl << endl;;//CSDN
//string容器的拼接操作 append
cout << "string容器的拼接操作" << endl ;
string str3 = "Go!";
str3 += str1;
cout << str3 << endl;//Go!hellow CSDN
string str4 = "Go!";
str4.append(str1, 7, 4);
cout << str4 << endl << endl;//Go!CSDN
//字符串的查找和替换find replace
cout << "字符串的查找和替换" << endl;
string str5 = "I love CS CSGO and CSDN";
int pos = str5.find("CS");//find从左边开始找第一次出现的 返回所在的编号
cout << pos << endl;//7
pos = str5.rfind("CS");//rfind查找最后一次出现的 返回所在的编号
cout << pos << endl;//14
string str6;
str6 = str5.replace(10, 4, "洛克王国");
cout << str6 << endl<<endl; //I love CS 洛克王国and CSDN
//字符串比较 compare
cout << "字符串比较" << endl;//相同返回0,左边大返回1,右边大返回-1
string stra = "random";
string strb = "random";
string strc = "peace";
if (stra.compare(strb)) {
cout << "stra大" << endl;
}
else if(stra.compare(strb) == 0) {
cout << "相等" << endl;
}
else {
cout << "strb大" << endl;
}
cout << endl << endl;
//字符串存取 []
cout << "字符串比较" << endl;
for (int i=0; i <str6.size(); i++) {
cout << str6[i];
}
str6[8] = 'f';
cout << endl<< str6 << endl << endl;//I love Cf 洛克王国 and CSDN
//字符串插入与删除 insert erase
cout << "字符串插入与删除" << endl;
str6.erase(10, 8);//一个汉字相当两个字符
cout << str6 << endl;//I love Cf and CSDN
str6.insert(10, "LOL");
cout << str6 << endl << endl;;//I love Cf LOL and CSDN
//字符串获取 substr(int pos,int len)//从那个位置开始几个
cout << "字符串获取" << endl;
string str7 = str6.substr(10, 3);
cout << str7 << endl << endl;
//小测试 "[email protected]"取出QQ邮箱的QQ号
string str = "[email protected]";
int pos1 = str.find("@");
string QQ = str.substr(0, pos1);
cout << QQ << endl;
}