string::rfind()函数和find()的使用
rfind()函数
找到字符串中最后一个和搜索字串一致的位置
size_t rfind (const string& str, size_t pos = npos) const; size_t rfind (const char* s, size_t pos = npos) const; size_t rfind (const char* s, size_t pos, size_t n) const; size_t rfind (char c, size_t pos = npos) const;
举例:
// string::rfind #include <iostream> #include <string> #include <cstddef> int main () { std::string str ("The sixth sick sheik's sixth sheep's sick."); std::string key ("sixth"); std::size_t found = str.rfind(key); if (found!=std::string::npos) str.replace (found,key.length(),"seventh"); std::cout << str << '\n'; return 0; }
输出:
The sixth sick sheik's seventh sheep's sick.
由于是rfind, 所以得到的是后面的sixth的位置, 如果使用find, 得到的就是前一个sixth的位置。

浙公网安备 33010602011771号