find
在string中,find函数被用于查找特定字符与特定字符串的位置,例如下面这段代码
#include<bits/stdc++.h>
using namespace std;
int main(){
string str = "hello,world";
int position = str.find("world");
cout << position;
return 0;
}
最后输出为6,意为"world"在str中第一次出现的位置是6。为什么要说是第一次呢?因为如果存在重复的查找对象,find只会返回第一次出现的位置,而当查找字符串不存在时,会返回-1。
下面是find的用法
假设str为一个字符串变量,我们需要在str里查找字符"w"
那么用法为:str.find("w");
此时返回的w的位置,为整型数据,只需定义一个整型变量用于存储。
erase
在string中,erase被用于删除特定字符和字符串,例如下面这段代码
#include<bits/c++std.h>
using namespace std;
int main(){
string str="hello,world";
str.erase(5,6);
cout<<str;
return 0;
}
输出结果为hello,不难看出erase的工作原理是通过输入要删除的字符或字符串的位置和该位置后的字符个数,达到删除从某个位置开始的某几个字符。
下面是erase的用法
假设str是一个字符串变量,需要删除其中的字符w
str=world;
str.erase(0,1);
最后输出orld,为什么起始位置是0?因为在string变量中的存储方式其实类似于数组,下标是从0开始而不是1,所以该语句的意思为从第0个字符开始,删除其后的一个字符,即为w。
find与erase的结合运用,修改字符串
例如下面的代码
#include<bits/c++.h>
using namespace std;
int main(){
string str1, str2;
str1 = "hello,world";
str2 = ",world";
int position = str1.find(str2);
str1.erase(5, 6);
cout << str1;
return 0;
}
最后结果为hello,该代码通过find查找",world"的位置,最后再用erase通过位置数据删除特定字符串,达到修改字符串的目的
我是初学者,该文为自用,如果您看到了不喜勿喷,有错误可以指正。