C++のcomparenocase関数の使い方は?

C++のcomparenoiselessは文字列を大文字小文字を無視して比較するための関数です。この関数は、通常文字列クラスのメンバ関数compareとともに使用されます。

comparenocase関数はC++標準ライブラリに直接実装されておらず、独自に実装する必要があります。以下はその実装例です。

#include <string>
#include <algorithm>

bool compareNoCase(const std::string& str1, const std::string& str2) {
    if (str1.length() != str2.length()) {
        return false;
    }
    
    return std::equal(str1.begin(), str1.end(), str2.begin(), [](char c1, char c2) {
        return std::tolower(c1) == std::tolower(c2);
    });
}

上記コードの `compareNoCase` 関数は2つの文字列ストリング `str1` と `str2` をパラメータとして取り、それらが等しいかどうかを (大文字と小文字の違いを無視して) 比較するものです。この関数はまず 2 つのストリングの長さを比較し、それらが等しくない場合は、それらは等しくないことを示し、直接 `false` を返します。次に、`std::equal` アルゴリズムを使用して 2 つのストリングの各文字を比較し、ラムダ関数を使用して文字を小文字に変換して比較します。

使用例:

std::string str1 = "Hello";
std::string str2 = "hello";

if (compareNoCase(str1, str2)) {
    std::cout << "Strings are equal (ignore case)" << std::endl;
} else {
    std::cout << "Strings are not equal" << std::endl;
}

比較対象の文字列の大小を無視して、compareNoCase関数が両者の等価を判定しているため、上記の例では「文字列は等しい(大文字と小文字は区別しない)」が出力されます。

bannerAds