内容:string的查找和替换操作。
#include <iostream>
#include <string>
using namespace std;
/*
查找函数:
1.find函数和rfind函数有多个重载版本,以下是基础运用。
2.find从字符串开头,从左往右查找;
rfind从字符串末尾,从右往左查找。
3.成功找到字符串则返回第一个字符的所在位置;
找不到则返回值-1。
4.字符串开头位置为0。
*/
void test01()
{
string str1 = "abcdddefgddd";
int pos1 = str1.find("ddd"); // here
cout << "pos1 = " << pos1 << endl;
int pos2 = str1.rfind("ddd"); // here
cout << "pos2 = " << pos2 << endl;
}
/*
替换函数:
1.replace在替换时,要指定从哪个位置开始,将多少个字符,替换成什么样的字符串。
2.替换后的字符串用 char*型 和 string型 均可
3.字符串开头位置为0。
*/
void test02()
{
string str2 = "aaaaaa";
str2.replace(1, 2, "bbbb"); // here,从str2的第1个位置开始 将2个字符 替换成新字符串
cout << "str2 = " << str2 << endl;
}
int main()
{
test01();
test02();
return 0;
}