温馨提示×

C++ string rfind如何确定搜索起点

c++
小樊
85
2024-07-19 03:19:39
栏目: 编程语言

在C++中,rfind函数用于在字符串中从右向左搜索指定子字符串,并返回其最后一次出现的位置。如果要指定搜索的起点,可以使用重载版本的rfind函数,该函数接受一个额外的参数作为搜索的起点位置。

例如,以下是使用重载版本的rfind函数来指定搜索起点的示例:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 搜索字符串中从位置5开始的子字符串"World"
    size_t pos = str.rfind("World", 5);
    
    if (pos != std::string::npos) {
        std::cout << "Found at position: " << pos << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }
    
    return 0;
}

在上面的示例中,rfind("World", 5)指定了从字符串的第5个位置开始搜索子字符串"World"。如果找到了子字符串,则返回其最后一次出现的位置;否则返回std::string::npos

0