string查找示例见下,代码见下,以及对应运行结果见下:
#include<iostream>
using namespace std;
int main() {
// 1
string s1 = "hellooooworld";
cout << s1.find("oooo") << endl;
// 2
cout << (int)s1.find("oooo", 8) << endl;
cout << s1.find("oooo", 4) << endl;
// 3
cout << s1.find('o') << endl;
cout << s1.find('o', s1.find('o') + 1) << endl;
// 4 从右向左查找
cout << s1.rfind("oo") << endl;
}
运行结果见下:
string数据替换,代码见下:
#include<iostream>
using namespace std;
int main() {
// 1
string s1 = "hello woooorld";
s1.replace(7, 5, "or"); // 代表从第七个元素开始,取五个字符,替换成对应字符
cout << s1 << endl;
// 2
s1 = "hello woooorld";
s1.replace(s1.begin()+7, s1.begin()+12, "or"); // 这个区间是左闭右开的,所以要到12
cout << s1 << endl;
// 3
s1 = "hello woooorld";
s1.replace(s1.begin() + 7, s1.begin() + 12, "or123edafsgsrg", 2);
cout << s1 << endl;
}
运行结果见下
string子串获取,代码见下:
#include<iostream>
using namespace std;
int main() {
// 1
string s1 = "hello woooorld";
string sub_s1 = s1.substr(7, 4);
cout << sub_s1 << endl;
// 2
string s2 = "xiaoxiaode&&yikeshu";
int pos = s2.find("&&");
string s3 = s2.substr(0, pos);
cout << s3 << endl;
}
运行结果见下