统计一个文本文件中,每个字母出现的次数(不区分大小写),要求以哈希表的方式实现。用c语言实现
时间: 2023-06-24 11:05:32 浏览: 103
统计字母出现的次数 C语言
5星 · 资源好评率100%
可以使用C语言中的哈希表来实现。哈希表是一种数据结构,可以通过哈希函数将键映射到索引,以快速地查找和访问数据。
以下是一个基本的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 50
// Define a struct for the hash table entry
typedef struct {
char* key;
int value;
} Entry;
// Define a struct for the hash table
typedef struct {
int size;
Entry* entries;
} HashTable;
// Hash function to map a key to an index
int hash(char* key, int size) {
int sum = 0;
for (int i = 0; i < strlen(key); i++) {
sum += tolower(key[i]);
}
return sum % size;
}
// Create a new hash table
HashTable* createHashTable(int size) {
HashTable* table = malloc(sizeof(HashTable));
table->size = size;
table->entries = calloc(size, sizeof(Entry));
for (int i = 0; i < size; i++) {
table->entries[i].key = NULL;
table->entries[i].value = 0;
}
return table;
}
// Insert a key-value pair into the hash table
void insert(HashTable* table, char* key, int value) {
int index = hash(key, table->size);
while (table->entries[index].key != NULL) {
if (strcmp(table->entries[index].key, key) == 0) {
table->entries[index].value += value;
return;
}
index = (index + 1) % table->size;
}
table->entries[index].key = strdup(key);
table->entries[index].value = value;
}
// Get the value associated with a key in the hash table
int get(HashTable* table, char* key) {
int index = hash(key, table->size);
while (table->entries[index].key != NULL) {
if (strcmp(table->entries[index].key, key) == 0) {
return table->entries[index].value;
}
index = (index + 1) % table->size;
}
return 0;
}
// Print the contents of the hash table
void printHashTable(HashTable* table) {
for (int i = 0; i < table->size; i++) {
if (table->entries[i].key != NULL) {
printf("%c: %d\n", *table->entries[i].key, table->entries[i].value);
}
}
}
int main() {
HashTable* table = createHashTable(26); // one slot for each letter of the alphabet
char filename[] = "test.txt";
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s\n", filename);
return 1;
}
char word[MAX_WORD_LENGTH];
while (fscanf(file, "%s", word) == 1) {
for (int i = 0; i < strlen(word); i++) {
if (isalpha(word[i])) {
char key[2];
key[0] = tolower(word[i]);
key[1] = '\0';
insert(table, key, 1);
}
}
}
fclose(file);
printHashTable(table);
return 0;
}
```
这个程序中,我们首先定义了一个 `Entry` 结构体来表示哈希表中的每个键值对,以及一个 `HashTable` 结构体来表示整个哈希表。然后,我们实现了一个哈希函数,它将一个字符串映射到一个索引。我们使用 `createHashTable` 函数来创建一个新的哈希表,并使用 `insert` 函数来将一个键值对插入哈希表中。最后,我们使用 `printHashTable` 函数来打印哈希表中每个字母出现的次数。
阅读全文