溫馨提示×

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

小億
148
2024-01-05 19:13:40
欄目: 編程語言

ReverseFind函數(shù)用于查找字符串中最后一個出現(xiàn)的指定字符或子字符串,并返回其位置。它的用法如下:

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

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

示例1:查找字符串中最后一個出現(xiàn)的字符

#include <iostream>
#include <string>

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

運行結(jié)果:

Character found at position: 7

示例2:查找字符串中最后一個出現(xiàn)的子字符串

#include <iostream>
#include <string>

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

運行結(jié)果:

Substring found at position: 6

需要注意的是,如果找不到指定的字符或子字符串,rfind函數(shù)會返回std::string::npos,可通過判斷pos是否等于npos來確定是否找到了字符或子字符串。

0