Search code examples
c++stringoperator-overloadingcomparison-operators

How do I overload the == operator for the string class in c++?


I am a new c++ programmer and I only recently learned about operator overloading. While working on an independent project I came across an issue, I wanted to compare user input strings with other strings in order to allow the user to navigate around a simple menu. The only thing is I don't know how to compare two strings while ignoring the case. If there is a much simpler way of doing this rather than overloading the == operator, please let me know but also let me know how to overload the == operator for strings because I am very interested.

What a great community. Thanks a lot guys, you answered my question very quick without making me feel dumb!


Solution

  • Well, I need to make several points here.

    • If by string you mean char arrays/pointers, then you cannot overload operator ==, since operator overloading is allowed only for user-defined types

    • If by strings you mean std::string, then you can't overload operator == either, since it is already overloaded :)

    • In order to do case-insensitive comparison, the best approach is to have a named function such as case_insensitive_equal. Boost has one - boost::iequals(str1, str2)

    • You could attempt to write your own char_traits to create a case insensitive string type

    As to how to write a function comparing strings in case insensitive manner, I'd do this:

    bool case_insensitive_equal(const std::string& s1, const std::string& s2)
    {
        if(s1.length() != s2. length())
           return false;
        for(int i = 0; i < s1.length(); ++i)
            if(std::toupper(s1[i]) != std::toupper(s2[i])) //tolower would do as well
                return false;
        return true;
    }
    

    Instead of loops you could use std::transform and std::equal,but I think this is more efficient.