0

I have a QHash<QString,QString>. I use the following expression to check whether a value is there in the QHash::keys() or not.

//programme
QHash<QString,QString> samplehash;
QString value = "somevalue";
if(samplehash.contains(value)) // Condition - 1
{
 //some code
}

Sometimes the above conditions matches, sometimes not for the same letters of different case. Is the QHash::contains method case-sensitive?

ymoreau
  • 3,402
  • 1
  • 22
  • 60
Ajay
  • 9,947
  • 8
  • 32
  • 34

3 Answers3

5

QHash.contains() is case sensitive as John T mentioned. Without the code there is not much to figure out. You can imagine it doing a == between the keys.

Please do not forget that accessing a non existent element via [] will create an empty entry in the hash, this might be what causes your bug. contains does not insert an entry into the hash, neither does value

Harald Scheirich
  • 9,676
  • 29
  • 53
2

It is case sensitive. The common practice for handling data from multiple sources and comparing it is to convert it all to the same format first, which usually involves making everything lowercase prior to comparison.

This is a common practice, especially on websites for handling logins, or user input in applications to avoid the old 'PEBKAC' situations and make it easier for users.

John T
  • 23,735
  • 11
  • 56
  • 82
  • But,the comparision works sometimes,and sometimes it does not. And i know,the keys in QHash do not change. The value part,can sometimes be lower-case or upper-case. – Ajay Jul 03 '09 at 06:43
0

One solution could be to subclass QString and override the operator== to do the comparison with case-insensitive mode, using QString::compare.

But the solution of John T is definitely better if it fits your constraints.

ymoreau
  • 3,402
  • 1
  • 22
  • 60
  • This is not working for me. `operator==` isn't called. (Of course, I overloaded the global `qHash` function, which is called.) – Thomas Klier Jun 25 '18 at 11:35
  • Alright, good to know, the operator seemed to be called by [`same_key`](https://code.woboq.org/qt5/include/qt/QtCore/qhash.h.html#_ZNK9QHashNode8same_keyEjRKT_) – ymoreau Jun 25 '18 at 12:26