findsun的专栏

--素心如何天上月

Use nocase string as g_hash_table's key

/* ghashtabledemo.c -- GHashTable demo */

#include <glib.h>
#include <string.h>

void print_entry(gpointer key, gpointer data, gpointer user_data)
{
  /* user_data not used */
  g_print("key: %-10s     value: %-10s/n", (gchar *)key, (gchar *)data);
}

guint g_str_case_hash (gconstpointer key) {
 gchar *upkey = g_ascii_strdown (key, strlen(key));
 guint hash = g_str_hash (upkey);
 g_free (upkey);
 return hash;
}

gboolean g_str_case_equal (gconstpointer a, gconstpointer b) {
 if (!g_ascii_strcasecmp (a, b))
  return TRUE;
 else
  return g_str_equal (a, b);
}

int main(int argc, char *argv[])
{
  GHashTable *hash1;
 
  hash1 = g_hash_table_new(g_str_case_hash, g_str_case_equal);

  /* insert a bunch of entries */
  g_hash_table_replace(hash1, g_strdup("foo"), g_strdup("bar"));
  g_hash_table_replace(hash1, g_strdup("FoO"), g_strdup("BAR"));
  g_hash_table_replace(hash1, g_strdup("more"), g_strdup("junk"));

  /* print the contents */
  g_print("Hash table entries:/n");
  g_hash_table_foreach(hash1, print_entry, NULL);

  return 0;
}

/*
 * gcc -ansi -Wall `pkg-config glib-2.0 --cflags` -o test test.c  `pkg-config glib-2.0 --libs`
 */

阅读更多
个人分类: Linux/Gnu/Gnome
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭