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 508
盖世英雄少女心
盖世英雄少女心 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 07:11

    Yes there is a case insensitive way to compare strings in C++. The key is that std::string is a template:

    template ,
              class Allocator = allocator>
    class basic_string;
    

    The traits here control how the charT's relate to each other. For normal std::string, they do what you'd expect, but we can just write our own traits that are case insensitive:

    struct case_insensitive_traits
    : char_traits
    {
        static bool eq(char a, char b) { return tolower(a) == tolower(b); }
        static bool ne(char a, char b) { return !eq(a, b); }
        static bool lt(char a, char b) { return tolower(a) < tolower(b); }
        static bool gt(char a, char b) { return tolower(a) > tolower(b); }
    
        static int compare(const char* a, const char* b, size_t n)
        {
            for (size_t i = 0; i < n; ++i) {
                int delta = tolower(a[i]) - tolower(b[i]);
                if (delta != 0) return delta;
            }
            return 0;
        }
    
        static const char* find(const char* s, size_t n, char c)
        {
            c = tolower(c);
            for (size_t i = 0; i < n; ++i, ++s) {
                if (tolower(*s) == c) return s;
            }
            return nullptr;
        }
    };
    

    With that:

    using case_insensitive_string = std::basic_string;
    
    case_insensitive_string a{"hello"};
    case_insensitive_string b{"hElLo"};
    
    assert(a == b);
    

提交回复
热议问题