以下分析仅仅从使用角度考虑,没有查看过内部实现
一、rfind()
1. rfind(str)
rfind(str)是从字符串右侧开始匹配str,并返回在字符串中的位置(下标);
附上测试代码:
# include<string>
# include<iostream>
using namespace std;
int main()
{
string str = "123456123456123456";
cout<<str<<endl<<"0123456789ABCDEFGHJ"<<endl;//方便查看上面字符串的下标
int pos = str.rfind("123");
cout<<pos<<endl;;
return 0;
}
运行结果:
2. rfind(str,pos)
rfind(str,pos)是从pos开始,向前查找符合条件的字符串;
附上测试代码:
# include<string>
# include<iostream>
using namespace std;
int main()
{
string str = "123456123456123456";
cout<<str<<endl<<"0123456789ABCDEFGHJ"<<endl;//方便查看上面字符串的下标
int pos = str.rfind("456",12);
cout<<pos<<endl;;
return 0;
}
运行结果:
那么问题来了,如果从pos开始,前面没有符合条件的字符串,会返回什么位置呢?
int pos = str.rfind("456",2);
运行结果:
返回无匹配项,即string::npos
另外,如果指定的位置,恰好处在原字符串中可以匹配的某一位置时呢?
int pos = str.rfind("456",3);//位置4,5,6返回值也相同
运行结果:
上面的情况是处在第一个可以匹配的子串当中,会返回该子串的位置,但如果是处于第二个可匹配的子串当中,那么又会返回什么呢?
int pos = str.rfind("456",9);//位置10,11,12返回值也相同
运行结果:
综上,可以得出rfind(str,pos)实际的开始的位置是,pos+str.size(),即从该位置开始(不包括该位置字符)向前寻找匹配项,如果有则返回字符串位置,如果没有则返回string::npos。
二、find()
1. find(str)
find()是返回第一次匹配字符串的位置,如果没有则返回string::npos。
附上测试代码:
# include<string>
# include<iostream>
using namespace std;
int main()
{
string str = "123456123456123456";
cout<<str<<endl<<"0123456789ABCDEFGHJ"<<endl;//方便查看上面字符串的下标
int pos = str.find("456");
cout<<pos<<endl;;
return 0;
}
运行结果:
2. find(str,pos)
find(str,pos)是用来寻找从pos开始(包括pos处字符)匹配str的位置。
附上测试代码:
# include<string>
# include<iostream>
using namespace std;
int main()
{
string str = "123456123456123456";
cout<<str<<endl<<"0123456789ABCDEFGHJ"<<endl;//方便查看上面字符串的下标
int pos = str.find("456",4);
cout<<pos<<endl;;
return 0;
}
运行结果:
下面验证是否包括pos处字符:
int pos = str.find("456",3);
运行结果:
综上,find(str,pos)是用来寻找从pos开始(包括pos处字符)匹配str的位置。