ReverseFindメソッドは、文字列内の最後の文字を探す方法です。

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と等しいかどうかを判断することで、文字やサブストリングが見つかったかどうかを確認できます。

bannerAds