溫馨提示×

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

c++
小樊
147
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女