版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37345402/article/details/83718774
string::npos参数 —— npos 是一个常数,用来表示不存在的位置
例如,有两个字符串a、b,判断a字符串是否包含b字符串
//如果字符串不存在包含关系,那么返回值就一定是npos
if(a.find(b)!=string::npos){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
string::size_type pos;
str.find("字符串") 返回值是字符在母串s中的下标位置;
str.find("字符串",9) 从s的下标9开始,查找字符串,返回字符串在s中的下标;
pos=s.find(str,pos) 查找s中str出现的所有位置。
pos=s.find_first_of(str) 返回str出现在母串s中的首次出现的位置
pos=s.find_last_of(str) 返回str出现在母串s中的最后一次出现的位置
#include<iostream>
#include<string>
using namespace std;
int main(){
string s("abcbcdcd");
string str="cd";
string::size_type pos;
pos=s.find("bc");
if(pos!=s.npos){
cout<<pos<<endl;//1
}else{
cout<<"no"<<endl;
}
pos=s.find("bc",2);
cout<<"从s下标2开始查找:"<<pos<<endl;//3
int i=1;
while((pos=s.find(str,pos))!=string::npos){
cout<<"位置"<<i<<":"<<pos<<endl;//位置1:4 位置2:6
pos++;
i++;
}
cout<<"第一次:"<<s.find_first_of('d')<<endl;//5
cout<<"最后一次:"<<s.find_last_of('d')<<endl;//7
}
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
#include<iostream>
#include<string>
using namespace std;
int main(){
string s("I love zufe.");
string::iterator it;
s.erase(1,5);//删除从1开始的5个字符
cout<<s<<endl;//I zufe.
it=s.begin()+6;
s.erase(it);//删除位置为9的字符
cout<<s<<endl;//I zufe
s.erase(s.begin()+3,s.end()-2);//删除之间的字符
cout<<s<<endl;//I zfe
}