36

I have to compare two Qstrings in qt,

say,

Qstring str1="1005",str2="1006";

I have tried using ,

if(str1==str2){
   return true;
}

&

if(str1.compare(str2)==0)
{
    return true;
}

still both methods goes inside if condition & returns true.

krohit
  • 792
  • 1
  • 7
  • 26

3 Answers3

52

You can use :

int x = QString::compare(str1, str2, Qt::CaseInsensitive);  // if strings are equal x should return 0
mcelik
  • 1,073
  • 2
  • 12
  • 22
  • 13
    Although the question asks how to compare strings, that's not *really* what it's asking since the question already demonstrates two ways of comparing strings, including the one suggested in this answer. The question means to ask why the comparisons appear to evaluate to unexpected results. Case sensitivity isn't involved in the example given. – Rob Kennedy Oct 09 '13 at 06:54
  • Third parameter can be changed according to how you want to compare them. I just gave an example of comparing strings. – mcelik Oct 09 '13 at 06:59
  • 1
    But the OP already has two examples of how to compare strings in his question, both of which are correct. So that is not the problem. – Benjamin Lindley Oct 09 '13 at 07:07
  • btw ur code is invalid because QString::compare isn't static, so u cannot use it as u wrote, it should be: int x = str1.compare(str2); – borune Jun 18 '19 at 07:23
17

The code below works fine for me.

int main(int argv, char **args)
 {
    QString str1="1005",str2="1006";
    if(str1 == str2)
        qDebug()<<"This should not print";
    qDebug()<<"Everything Ok";

}

Output:

Everything Ok

The == operator is overloaded for QStrings, as documented here.

I don't know why your code is not working. Recheck other parts of your code.

markasoftware
  • 12,292
  • 8
  • 41
  • 69
Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39
0

It worked after Rebuilding the Project , I think this is the problem with QT CREATOR

krohit
  • 792
  • 1
  • 7
  • 26
  • 8
    This doesn't answer how to compare two QT strings. It seemly shows that you had some temporary environment problems. – Maxim Kornilov Dec 08 '14 at 10:11
  • 18
    @Maxim It doesnt mean that u'll downvote.I have posted here because I was not able to figure out the weird behavior of Qt. But if it got solved by fixing some environment related issue then it is my responsibility to let people know that it was my fault & close this thread. – krohit Dec 09 '14 at 11:38
  • @Maxim is correct. This answer is not useful. Hence the downvotes. – Laszlo Jan 07 '20 at 02:31
  • 1
    Not an answer, but might have been included as an update to the question – AlainD Jul 13 '20 at 14:55