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;
- }
#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;
}
</div>
</article>
补充
/*string (1)*/ size_t rfind (const string& s, size_t pos = npos) const noexcept;
/*c-string (2)*/ size_t rfind (const char* s, size_t pos = npos) const;
/*buffer (3)*/ size_t rfind (const char* s, size_t pos, size_t n) const;
/*character (4)*/ size_t rfind (char s, size_t pos = npos) const noexcept;
上述中的pos参数表示反向查找的区间为[0, pos],但是实际上rfind
使用的查找区间是[0, pos + s.size() - 1],当pos < 0
的时候等效于pos == npos
。