string字符串在C++中不能直接进行切片操作,需要借助函数find和substr进行
1.substr用于进行已知序号的切片操作
substr语法为 :
string对象.substr(起点 , 切片长度)
operate_str = initial_str.substr(0, 3);
代码演示如下
//使用substr函数实现已知序号的字符串切片
string initial_str = "0123456789";
string operate_str;
operate_str = initial_str.substr(0, 3); //从0号开始,切片长度为3,即截取0到(0 + 3 - 1)号
cout << "operate_str = " << operate_str << endl; //输出结果为012
2.find函数和substr函数配合用于进行已知特征字符串的字符串切片
find函数处理对象中存在特征字符串时返回特征串第一个字符的序号,若对象中不存在特征字符串则返回-1
find函数语法为:
string对象.find(特征字符串)
int start = initial_str.find(key1);
以下配合substr实现已知特征字符串的字符串切片
//使用substr函数配合find函数实现已知特征串的字符串切片
string key1 = "23"; //定义特征串
int len = 5; //定义切片长度
int start = initial_str.find(key1); //返回特征串第一个字符的序号,此处为2
string key2 = "abc"; //测试不存在特征串返回值
int result = initial_str.find(key2);
cout << "result = " << result << endl; //对象中不存在特征串,此处输出为 -1
operate_str = initial_str.substr(start, len); //从start开始,切片长度为len,即截取start到(start + len - 1)号
cout << "operate_str = " << operate_str << endl; //输出结果为23456
(变量与只使用substr时相同)