#include<bits/stdc++.h>
using namespace std;
int main(){
/* string a = "abcdefg";
string b = "abc";
int leng = b.size();
int leng = a.length();//获取字符串长度
printf("%s\n", a.c_str());//将string变为字符数组
//string与vector一样,支持对迭代器进行加减某个数字。
//str1+str2, str1+=str2
//可比较大小,比较规则:字典序
//插入
string str = "abcxyz", str2 = "opq";
str.insert(3, str2); //str[3]处插入str2
str.insert(str.begin(), str2.begin(), str2.end());
cout << str << endl;
str.erase(str.begin()+4);
str.erase(str.begin()+3, str.end());//删除[ , )左闭右开
cout << str << endl;
//clear()
str.clear();
*/
//substr() 子串
string str = "abcdefg";
string str2 = "abc";
cout << str.substr(0, 3) << endl; //返回0位置开始,长度为3的子串
int index = str.find(str2); //查找子字符串所在的第一次出现的所在下标位置
int index2 = str.find(str2, 3); //从3号位置开始匹配子串str2
cout << str[index] << endl; //不是子串时返回string::npos (常数:-1 或者 4294967295)
//replace()
string str3 = "Maybe you will turn around.";
string str4 = "will not";
string str5 = "surely";
cout << str3.replace(10, 4, str4) << endl; //从10号位置开始,长度为4的子串被替换为str2
cout << str3.replace(str3.begin(), str3.begin()+5, str5) << endl; //左闭右开
return 0;
}
string字符串操作
最新推荐文章于 2023-08-15 16:41:19 发布