vicatcu vicatcu - 2 months ago 26
C++ Question

Qt String Comparison

Suppose I have:

QVariant x;


... and assuming the following statement holds true:

x.canConvert<QString>() == true


Is the following code fragment:

if(x.toString().compare("abcdefg") == 0){
doSomething();
}
else{
doSomethingElse();
}


... functionally equivalent to:

if(x.toString() == "abcdefg"){
doSomething();
}
else{
doSomethingElse();
}


I could prove this for myself by writing a fairly trivial program and executing it, but I was surprised I couldn't find the question / answer here, so I thought I'd ask it for the sake of future me / others.

Answer

QString::compare will only return zero if the string passed to it and the string it is called on are equal.

Qstring::operator== returns true if the strings are equal otherwise, false.

Since compare only returns zero when the strings are equal then

(qstrign_variable.compare("text") == 0) == (qstrign_variable == "text")

If qstrign_variable contains "text" in the above example. If qstrign_variable contains something else then both cases evaluate to false.

Also note that std::string has the same behavior

Comments