c语言输入多行英文句子,输出不重复单词的个数
时间: 2024-03-07 16:48:28 浏览: 24
可以使用哈希表来实现这个功能,具体步骤如下:
1. 定义一个哈希表,用于存储单词及其出现次数。
2. 读入多行英文句子,逐行处理每个单词。
3. 对于每个单词,判断它是否已经在哈希表中出现过。如果是,将该单词的出现次数加1;否则,在哈希表中添加该单词,并将出现次数设为1。
4. 处理完所有单词后,遍历哈希表,输出出现次数为1的单词个数即可。
以下是使用C语言实现的代码示例:
```c
#include <stdio.h>
#include <string.h>
#define HASH_SIZE 10007
struct node {
char word[50];
int count;
struct node* next;
};
struct node* hashtable[HASH_SIZE];
unsigned int hash(char* str) {
unsigned int h = 0;
while (*str) {
h = (h << 5) + h + *str++;
}
return h % HASH_SIZE;
}
void insert(char* str) {
unsigned int h = hash(str);
struct node* p = hashtable[h];
while (p) {
if (strcmp(p->word, str) == 0) {
p->count++;
return;
}
p = p->next;
}
p = (struct node*)malloc(sizeof(struct node));
strcpy(p->word, str);
p->count = 1;
p->next = hashtable[h];
hashtable[h] = p;
}
int main() {
char line[1000], word[50];
int i, j, len, count = 0;
while (fgets(line, sizeof(line), stdin)) {
len = strlen(line);
if (len > 0 && line[len-1] == '\n') {
line[len-1] = '\0';
}
j = 0;
for (i = 0; line[i]; i++) {
if (line[i] == ' ') {
word[j] = '\0';
if (j > 0) {
insert(word);
j = 0;
}
} else {
word[j++] = line[i];
}
}
word[j] = '\0';
if (j > 0) {
insert(word);
}
}
for (i = 0; i < HASH_SIZE; i++) {
struct node* p = hashtable[i];
while (p) {
if (p->count == 1) {
count++;
}
p = p->next;
}
}
printf("%d\n", count);
return 0;
}
```
该程序使用了一个大小为10007的哈希表来存储单词及其出现次数。在读入每个单词时,先计算哈希值,然后在哈希表中查找该单词是否已经出现过。如果已经出现过,将该单词的出现次数加1;否则,在哈希表中添加该单词,并将出现次数设为1。最后,遍历哈希表,统计出现次数为1的单词个数,并输出结果。