Case insensitive std::string.find()

前端 未结 10 1996
挽巷
挽巷 2020-11-27 02:47

I am using std::string\'s find() method to test if a string is a substring of another. Now I need case insensitive version of the same thing. For s

10条回答
  •  时光说笑
    2020-11-27 03:23

    Since you're doing substring searches (std::string) and not element (character) searches, there's unfortunately no existing solution I'm aware of that's immediately accessible in the standard library to do this.

    Nevertheless, it's easy enough to do: simply convert both strings to upper case (or both to lower case - I chose upper in this example).

    std::string upper_string(const std::string& str)
    {
        string upper;
        transform(str.begin(), str.end(), std::back_inserter(upper), toupper);
        return upper;
    }
    
    std::string::size_type find_str_ci(const std::string& str, const std::string& substr)
    {
        return upper(str).find(upper(substr) );
    }
    

    This is not a fast solution (bordering into pessimization territory) but it's the only one I know of off-hand. It's also not that hard to implement your own case-insensitive substring finder if you are worried about efficiency.

    Additionally, I need to support std::wstring/wchar_t. Any ideas?

    tolower/toupper in locale will work on wide-strings as well, so the solution above should be just as applicable (simple change std::string to std::wstring).

    [Edit] An alternative, as pointed out, is to adapt your own case-insensitive string type from basic_string by specifying your own character traits. This works if you can accept all string searches, comparisons, etc. to be case-insensitive for a given string type.

提交回复
热议问题