Pregunta

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!

¿Fue útil?

Solución

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.

Otros consejos

You don't overload operator== for std::string because you would have to put the operator into the std namespace. This is (a) not allowed and (b) has already been done by the standard library implementation.

It is also inadvisable to overload any operator== to mean anything other than a true equality. I.e. if a == b then a and b should behave identically.

What you should prefer to do is write a separate function with a meaningful name, e.g.

bool areEqualIgnoringCase(const std::string&, const std::string&);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top