C++ string rfind如何定位子字符串

   2024-10-06 5450
核心提示:在C++中,可以使用string类的rfind方法来定位子字符串在字符串中最后一次出现的位置。rfind方法的语法如下:size_t rfind (const

在C++中,可以使用string类的rfind方法来定位子字符串在字符串中最后一次出现的位置。rfind方法的语法如下:

size_t rfind (const string& str, size_t pos = npos) const noexcept;

其中,str为要查找的子字符串,pos为开始查找的位置,默认值为npos,表示从末尾开始查找。

举个例子,假设我们有一个字符串str = “hello world, hello c++”,要查找子字符串"hello"在str中最后一次出现的位置,可以这样做:

#include <iostream>#include <string>int main() {    std::string str = "hello world, hello c++";    std::string subStr = "hello";    size_t pos = str.rfind(subStr);    if (pos != std::string::npos) {        std::cout << "子字符串在位置:" << pos << std::endl;    } else {        std::cout << "未找到子字符串" << std::endl;    }    return 0;}

在以上示例中,rfind方法会返回子字符串"hello"在字符串str中最后一次出现的位置,即23。如果子字符串不存在于字符串中,则返回npos。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号