ReverseFind的用法,查找字符中最后一个字符

   2025-02-13 8820
核心提示:ReverseFind函数用于查找字符串中最后一个出现的指定字符或子字符串,并返回其位置。它的用法如下:int ReverseFind(const char*

ReverseFind函数用于查找字符串中最后一个出现的指定字符或子字符串,并返回其位置。它的用法如下:

int ReverseFind(const char* str, char c);int ReverseFind(const char* str, const char* subStr);

其中,str是要查找的字符串,c是要查找的字符,subStr是要查找的子字符串。

示例1:查找字符串中最后一个出现的字符

#include <iostream>#include <string>int main() {    std::string str = "Hello world!";    char c = 'o';    int pos = str.rfind(c);  // 使用rfind函数查找字符    if (pos != std::string::npos) {        std::cout << "Character found at position: " << pos << std::endl;    } else {        std::cout << "Character not found." << std::endl;    }    return 0;}

运行结果:

Character found at position: 7

示例2:查找字符串中最后一个出现的子字符串

#include <iostream>#include <string>int main() {    std::string str = "Hello world!";    std::string subStr = "world";    int pos = str.rfind(subStr);  // 使用rfind函数查找子字符串    if (pos != std::string::npos) {        std::cout << "Substring found at position: " << pos << std::endl;    } else {        std::cout << "Substring not found." << std::endl;    }    return 0;}

运行结果:

Substring found at position: 6

需要注意的是,如果找不到指定的字符或子字符串,rfind函数会返回std::string::npos,可通过判断pos是否等于npos来确定是否找到了字符或子字符串。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言