string 字符串处理在所有的语言中都非常重要,在刷题时也会专门有一类字符串处理的题,学会了string中的常用方法,肯定会帮助我们在刷题的过程中事半功倍。
首先我们定义一个string变量,后面的方法都是基于str_mother进行的。
string str_mother;
1、str_mother.find(str_son,pos) 从pos位置开始从前往后查找str_mother中是否存在str_son,若存在则返回其起始地址,反之则返回string::npos。
string str = "Berlin&&Berlin";
//查找字符在母串中第一次出现的位置 输出5
cout<<str.find('n')<<endl;
//查找字符串在母串中第一次出现的位置的位置 输出3
cout<<str.find("lin")<<endl;
2、str_mother.rfind(str_son,pos) 从pos位置开始从后往前查找str_mother中是否存在str_son,若存在则返回其起始地址,反之则返回string::npos。
string str = "Berlin&&Berlin";
//查找字符在母串中第一次出现的位置 输出13
cout<<str.rfind('n')<<endl;
//查找字符串在母串中第一次出现的位置的位置 输出11
cout<<str.rfind("lin")<<endl;
技巧:我们可以通过组合使用find()与rfind()来实现判断该子串是否唯一存在于母串中
bool Judge_Only(string str_son,string str_monther){
return str_monther.find(str_son) == str_monther.rfind(str_son);
}
3、str_mother.find_last_of(str_son)&&str_mother.find_first_of(str_son)
find_last_of()函数是找这个子串在母串中最后一次出现的位置并且将该位置返回;而find_first_of()函数是找这个子串在母串中最后一次出现的位置并将该位置返回,
//查找字符在母串中第一次出现的位置
cout<<str.find_first_of('n')<<endl;
//查找字符在母串中最后一次出现的位置
cout<<str.find_last_of('n')<<endl;
4、str_mother.substr(pos,len) 返回str_mother中从pos位置开始的长度为len的子串。
5、str_mother.insert(pos,str)在str_mother中的pos位置插入str。
6、str_mother.erase(pos,len)删除str_mother中从pos位置开始的长度为len的子串。
7、str_mother.replace(pos,len,str)将str_mother从pos位置开始长度为len的子串替换为str;
//返回str中从pos开始长度为len的子串
cout<<str.substr(pos,len)<<endl;
//删除从pos开始长度为len的子串
str.erase(pos,len);
str.insert(0,"Be");
str.replace(str.find("Berlin"),5,"yanan");
测试完整代码:
#include<bits/stdc++.h>
using namespace std;
bool Judge_Only(string str_son,string str_monther){
return str_monther.find(str_son) == str_monther.rfind(str_son);
}
int main(){
string str = "Berlin&&Berlin";
int pos=0,len=2;
//查找字符在母串中第一次出现的位置
cout<<str.find('n')<<endl;
//查找字符在母串中第一次出现的位置
cout<<str.find_first_of('n')<<endl;
//查找字符在母串中最后一次出现的位置
cout<<str.find_last_of('n')<<endl;
//查找字符串在母串中第一次出现的位置的位置
cout<<str.find("lin")<<endl;
//从串尾向前查找字符串在母串中第一次出现的位置的位置
cout<<str.rfind("lin")<<endl;
//若在母串中查找不到该子串,那么返回string::npos(一个大整数)
cout<<"The integral form of string::npos:"<<str.find("yanan")<<endl;
//返回str中从pos开始长度为len的子串
cout<<str.substr(pos,len)<<endl;
//删除从pos开始长度为len的子串
str.erase(pos,len);
cout<<str<<endl;
str.insert(0,"Be");
cout<<str<<endl;
str.replace(str.find("Berlin"),5,"yanan");
cout<<str<<endl;
if(str.find("yanan")==string::npos)
printf("return string::npos\n");
else
printf("find success\n");
if(Judge_Only("lin",str)) cout<<"Only you\n"<<endl;
else cout<<"not only you\n"<<endl;
}
运行结果: