C++ std::string::rfind() 查找子串或字符最后一次出现的下标。可选第二参数给出搜索的最右起点。
原型
size_t rfind(const string& str, size_t pos = npos) const;
size_t rfind(char c, size_t pos = npos) const;参数
str/c:要查找的内容。pos:从此下标向左考虑,默认从末尾开始。
返回值
成功返回匹配下标;失败返回 npos。
示例
#include <iostream>
#include <string>
int main() {
std::string s = "a.cpp / b.cpp";
auto p = s.rfind(".cpp");
if (p != std::string::npos) {
std::cout << p << std::endl;
}
return 0;
}输出:
9
注意事项
rfind 返回的仍是从左起算的下标,只是匹配取最右侧那一次。提取扩展名时,常与 substr 联用。
下一页介绍substr:按位置截取子串。