string查找和替换
查找:查找指定字符串是否存在
替换: 在指定位置替换字符串
1.查找
#include<iostream>
#include<string.h>
using namespace std;
void test01(){
string str1="abcdefg";
int pos=str1.find("df");
cout<<pos<<endl;
}
int main()
{
test01();
return 0;
}
因为找不到df串,所以输出-1。
rfind从右到左,find从左往右
#include<iostream>
#include<string.h>
using namespace std;
void test01(){
string str1="abcdefg";
int pos=str1.find("de");
cout<<pos<<endl;
int pos1=str1.rfind("de");
cout<<pos1<<endl;
}
int main()
{
test01();
return 0;
}
改动一下字符串 str1="abcdefg"改为str2=“abcdefgde”
运行结果
可以看出,rfind和find的区别
2.替换
#include<iostream>
#include<string.h>
using namespace std;
void test01(){
string str1="abcdefgde";
str1.replace(1,3,"1111");//把原来字符串的三个字符替换成四个字符
cout<<str1<<endl;
}
int main()
{
test01();
return 0;
}