溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C語言字符串的哈希計算與應用

發(fā)布時間: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創(chuàng)建。
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創(chuàng)建。
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;
}

這個示例中,我們創(chuàng)建了一個簡單的哈希表,并使用DJB2哈希函數將字符串存儲在哈希表中。然后,我們使用相同的哈希函數從哈希表中獲取字符串。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI