目录
1. 构建操作
void Test1()
{
cout << endl << "构造操作: " << endl;
string s1; //默认构造
string s2(10, 'a'); //有参
string s3("asdfgh"); //传字符串初始化
string s4(s3); //拷贝构造
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << endl;
}
2.赋值操作
void Test2()
{
cout << endl << "赋值操作: " << endl;
string s1; //默认构造
string s2("s2"); //传字符串初始化
s1 = "s2"; //字符串
cout << s1 << endl;
s1 = s2; //string类
cout << s1 << endl;
s1 = 'a'; //字符
cout << s1 << endl;
s1.assign("s2"); //成员
cout << s1 << endl;
}
3.取值操作
void Test3()
{
cout << endl << "取值操作: " << endl;
string s1("asdfgh");
//访问越界,直接崩溃
for (int i = 0; i < s1.size(); i++) {
cout << s1[i] << " ";
}
cout << endl;
//访问越界,抛出异常out_of_range
for (int i = 0; i < s1.size(); i++) {
cout << s1.at(i) << " ";
}
cout << endl;
try {
cout << s1.at(100) << endl; //抛出异常
}
catch (...) {
cout << "访问越界" << endl;
}
}
4.拼接操作
void Test4()
{
cout << endl << "拼接操作: " << endl;
string s1("asdfgh");
s1 += "test1";
cout << s1 << endl;
string s2 = "test2";
s1 += s2;
cout << s1 << endl;
string s3 = "test3";
s1.append(s3);
cout << s1 << endl;
}
5.查找操作
void Test5()
{
cout << endl << "查找操作: " << endl;
string s1("asdfghdf");
int pos = s1.find("df"); //第一次出现的位置
cout << pos << endl;
pos = s1.rfind("df"); //最后一次出现的位置
cout << pos << endl;
}
6.替换操作
void Test6()
{
cout << endl << "替换操作: " << endl;
string s1("asdfghdf");
s1.replace(0, 3, "111"); //从序号0开始的3个字符
cout << s1 << endl;
}
7.比较操作
void Test7()
{
cout << endl << "比较操作: " << endl;
string s1("asdfghdf");
string s2("asdfghdf");
if (!s1.compare(s2)) {
cout << "相同" << endl;
} else {
cout << "不相同" << endl;
}
}
8.子串操作
void Test8()
{
//string substr(int pos = 0, int n = count) const 返回pos开始的n个字符组成的字符子串
cout << endl << "子串操作: " << endl;
string s1("asdfghdf");
cout << "从2开始的3个字符组成的子串: " << s1.substr(2, 3) << endl;
}
9.插入删除操作
void Test9()
{
//void insert(int pos, string str)
//void erase(int pos, string str)
cout << endl << "插入删除操作: " << endl;
string s1("asdfghdf");
s1.erase(0, 4);
cout << s1 << endl;
s1.insert(0, "asdf");
cout << s1 << endl;
}