c++string容器
//string是一个类,封装了char *,是一个char *型的容器
//string封装了很多成员方法
//查找find,拷贝copy,删除delete,替换replace,插入insert
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
//赋值操作
s1 = "abc";
//取值操作
//1.[]取值,越界程序崩溃
cout << s1[0] << endl;
//2.at()方法取值,越界抛异常out_of_range
try {
cout << s1.at(100) << endl;
}
catch (...) {
cout << "下标越界" << endl;
}
//拼接操作,从末尾开始拼接
string s2 = "qwe";
s1 = s1 + s2;
s1.append(s2);//把s2添加到s1的尾部
cout << s1 << endl;
//string子串查找
string s3 = "sdfgytrewfg";
//查找第一次"fg"出现的位置
int pos = s3.find("sd");//find方法返回位置,即下标
cout << "第一次出现位置为:" << pos << endl;
//朝赵最后一次"fg"出现的位置
pos = s3.rfind("fg");//rfind从后往前找,并返回位置,即下标
cout << "最后一次出现位置为:" << pos << endl;
//string替换
string s4 = "abcdefg";
s4.replace(0, 2, "2233");//这句话的意思是从s4容器的下标0开始,替换两个元素,即"ab",替换为"2233"
cout << s4 << endl;
//string比较,>时返回1,<小于时返回-1,==时返回0
string s5 = "1111";
string s6 = "2222";
if (s1.compare(s2) == 0)
{
cout << "字符串相等" << endl;
}
else
{
cout << "字符串不相等" << endl;
}
//string子串截取
string s7 = "abcdef";
string s8 = s7.substr(0, 3);//从下标0开始,截取3个字符,包括下标为0的字符
cout << s8 << endl;
//string插入和删除
string s9 = "111222333";
s9.insert(3, "aaa");//从下标为3的元素开始插入,后面为插入的字符串
cout << s9 << endl;
s9.erase(3, 3);//从下标为3的元素开始删除,删除3个元素
cout << s9 << endl;
return 0;
}