string中的find函数与rfind函数定义如下:
int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
//查找成功时返回所在位置,失败返回string::npos的值
int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置
int rfind(const char *s, int pos = npos) const;
int rfind(const char *s, int pos, int n = npos) const;
int rfind(const string &s,int pos = npos) const;
在实际的程序实现中,rfind的查找截止值并不是pos,而是pos+strlen(c)-1。
#include<iostream>
using namespace std;
int main()
{
string st = "1111111111"; //10个字符
cout<< st.rfind("1111",9) << endl; //按照定义应返回6,正确
cout<< st.rfind("1111",7) << endl; //按照定义应返回4,实际是6
cout<< st.rfind("1111",5) << endl; //按照定义应返回2,实际是5
cout<< st.rfind("1111",2) << endl; //按照定义应返回-1,实际是2
return 0;
}