c++

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

小樊
86
2024-07-19 03:10:36
栏目: 编程语言

在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。

0
看了该问题的人还看了