views:

393

answers:

2

Is there any simply way how to create a case insensitive (String -> String) Glib Hash Table?

The result should fit this:

GHashTable *table;
//there should be definition of table

g_hash_table_insert(table, "KeY", "Something"); //insert

//every command should return the line in table
g_hash_table_lookup(table, "Key");
g_hash_table_lookup(table, "KEY");
g_hash_table_lookup(table, "key");
g_hash_table_lookup(table, "KeY");

I think the problem is only in definition of hash function and comparement function. However, I don't know which functions I should use.

+3  A: 

Why don't you just transform the key using something like tolower() ? That way the key is standardized, and hence your hash table will be too.

Dirk Eddelbuettel
That requires either that all users are responsible for using lower case keys, or that all the hashtable ops are placed in wrappers which copy the string to lowercase it. Nothing inherently wrong with either option, but if they're not convenient, GHashTable is designed to allow exactly what the OP asks for.
Steve Jessop
+2  A: 

Provide your own equality and hash functions to g_hash_table_new, instead of g_str_equal and g_str_hash.

Probably the easiest way to write the hash is to take a copy of the source for g_str_hash, but on reading each char, push it to lower case before continuing. But there are any number of string hashing algorithms that you could use, just adapt one to ensure that two strings which differ only by case will result in the same hash value.

As long as you only need to worry about ASCII strings, you can almost (but not quite) use g_ascii_strcasecmp for the equality function. You need to adjust the return value. If you want to support a bigger character set, use a case-insensitive comparison for that set.

Steve Jessop