现在的位置: 首页 > 综合 > 正文

Use nocase string as g_hash_table’s key

2013年09月10日 ⁄ 综合 ⁄ 共 1000字 ⁄ 字号 评论关闭

/* 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`
 */

【上篇】
【下篇】

抱歉!评论已关闭.