Is there a built in function for std::string in C++ to compare two strings alphabetically when either string can be uppercase or lowercase?

后端 未结 5 512
盖世英雄少女心
盖世英雄少女心 2021-01-18 06:08

I know for C++ that basic comparative operators can accomplish the task if both words are either entirely lower or entirely upper case. I have an array of strings and letter

5条回答
  •  伪装坚强ぢ
    2021-01-18 06:52

    I don't know of any case-insensitive functions in the standard library, but you can specify a custom predicate for std::equal:

    std::string a("hello");
    std::string b("HELLO");
    std::cout << std::equal(a.begin(), a.end(), b.begin(),
        [] (const char& a, const char& b)
        {
            return (std::tolower(a) == std::tolower(b));
        });
    

    For a solution which takes locale into account, refer to Case insensitive std::string.find().

    #include 
    
    template
    struct my_equal {
        my_equal( const std::locale& loc ) : loc_(loc) {}
        bool operator()(charT ch1, charT ch2) {
            return std::toupper(ch1, loc_) == std::toupper(ch2, loc_);
        }
    private:
        const std::locale& loc_;
    };
    
    int main()
    {
        std::string a("hello");
        std::string b("HELLO");
        std::cout << std::equal(a.begin(), a.end(), b.begin(),
            my_equal<>(std::locale()));
    }
    

提交回复
热议问题