string查找和替换

#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm> //标准算法的头文件
//字符串查找和替换
//1、查找
void test01()
{
string str1="abcdefgde";
int pos=str1.find("de");//没有返回-1
if (pos==-1)
{
cout<<"未找到字符串"<<endl;
}
else
{
cout<<"找到字符串pos="<<pos<<endl;
}
//rfind
//rfind 和find区别
//rfind是从右往左查找 find从左往右查找
pos=str1.rfind("de");
cout<<"pos="<<pos<<endl;
}
//2、替换
void test02()
{
string str1="abcdefg";
str1.replace(1,3,"1111");
cout<<"str1="<<str1<<endl;
}
int main()
{
test01();
test02();
return 0;
}
总结:
find查找是从左往后,rfind从右往左
find找到字符串后返回查找的第一个字符的位置,找不到返回-1
replace在替换时,要指定从哪个位置起,多少个字符,替换成什么样的字符串

浙公网安备 33010602011771号