string查找和替换
功能描述:
查找:查找指定字符串是否存在
替换:在指定的位置替换字符串
函数原型:
rfind 和find 的区别:
rfind从右往左查找 find从左往右查找
查找案列代码如下:
#include <iostream>
using namespace std;
#include <cstring>//字符串查找和替换
//1.查找
void test01() {//findstring str1 = "abcdefgde";int pos = str1.find("de");//返回第一次出现的位置cout << "pos = " << pos << endl;pos = str1.find("df");//返回-1表示没找到cout << "pos = " << pos << endl;if (pos == -1) {cout << "未找到" << endl;} else {cout << "找到了" << endl;}//rfindpos = str1.rfind("de");cout << "pos = " << pos << endl;//rfind和find的区别、//rfind从右往左查找 find从左往右查找}int main() {test01();return 0;
}
替换案列代码如下:
#include <iostream>
using namespace std;
#include <cstring>//字符串查找和替换
//2.替换
void test01() {string str1 = "abcdefg";str1.replace(1, 3, "1111");cout << "str1 = " << str1 << endl;}int main() {test01();return 0;
}