温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言字符串的哈希计算与应用

发布时间:2024-08-30 13:29:57 来源:亿速云 阅读:80 作者:小樊 栏目:编程语言

在C语言中,字符串的哈希计算是将一个字符串映射到一个整数值,通常用于在数据结构(如哈希表)中快速查找和存储

  1. 简单哈希函数: 这是一个简单的哈希函数,逐个字符地累加字符串中的字符。
unsigned int simple_hash(const char *str) {
    unsigned int hash = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        hash += str[i];
    }
    return hash;
}
  1. DJB2哈希函数: DJB2哈希函数是一种较为常用的哈希函数,由Daniel J. Bernstein创建。
unsigned int djb2_hash(const char *str) {
    unsigned int hash = 5381;
    int c;
    while ((c = *str++)) {
        hash = ((hash << 5) + hash) + c; // hash * 33 + c
    }
    return hash;
}
  1. SDBM哈希函数: SDBM哈希函数是一种简单且快速的哈希函数,由Daniel J. Bernstein创建。
unsigned int sdbm_hash(const char *str) {
    unsigned int hash = 0;
    int c;
    while ((c = *str++)) {
        hash = c + (hash << 6) + (hash << 16) - hash;
    }
    return hash;
}
  1. 使用哈希函数: 以下是一个简单的示例,展示了如何使用哈希函数将字符串存储在哈希表中。
#include<stdio.h>
#include <stdlib.h>
#include<string.h>

typedef struct HashNode {
    char *key;
    char *value;
    struct HashNode *next;
} HashNode;

HashNode *create_node(const char *key, const char *value) {
    HashNode *node = (HashNode *)malloc(sizeof(HashNode));
    node->key = strdup(key);
    node->value = strdup(value);
    node->next = NULL;
    return node;
}

void insert(HashNode **table, const char *key, const char *value, unsigned int (*hash_func)(const char *)) {
    unsigned int index = hash_func(key) % 100;
    HashNode *node = table[index];

    if (!node) {
        table[index] = create_node(key, value);
    } else {
        while (node->next) {
            if (strcmp(node->key, key) == 0) {
                free(node->value);
                node->value = strdup(value);
                return;
            }
            node = node->next;
        }
        node->next = create_node(key, value);
    }
}

char *get(HashNode **table, const char *key, unsigned int (*hash_func)(const char *)) {
    unsigned int index = hash_func(key) % 100;
    HashNode *node = table[index];

    while (node) {
        if (strcmp(node->key, key) == 0) {
            return node->value;
        }
        node = node->next;
    }
    return NULL;
}

int main() {
    HashNode *table[100] = {NULL};

    insert(table, "hello", "world", djb2_hash);
    printf("Value of 'hello': %s\n", get(table, "hello", djb2_hash));

    return 0;
}

这个示例中,我们创建了一个简单的哈希表,并使用DJB2哈希函数将字符串存储在哈希表中。然后,我们使用相同的哈希函数从哈希表中获取字符串。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI