用C语言写一个代码,要求在文件中找出所有出现该单词的句子及单词出现的位置,并且统计该单词出现的次数
时间: 2023-12-09 13:05:16 浏览: 82
以下是一个用 C 语言实现的代码,可以在文本文件中查找指定单词,并输出包含该单词的句子、单词出现的位置和出现次数。
```c
#include <stdio.h>
#include <string.h>
#define MAX_SENTENCE_LEN 1000
#define MAX_WORD_LEN 50
#define FILE_NAME "text.txt"
int main() {
char sentence[MAX_SENTENCE_LEN];
char word[MAX_WORD_LEN];
int word_count = 0;
FILE *fp;
printf("Enter a word to search: ");
scanf("%s", word);
fp = fopen(FILE_NAME, "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
while (fgets(sentence, MAX_SENTENCE_LEN, fp) != NULL) {
int sentence_len = strlen(sentence);
int word_len = strlen(word);
for (int i = 0; i < sentence_len - word_len; i++) {
if (strncmp(sentence + i, word, word_len) == 0) {
printf("Sentence: %s\n", sentence);
printf("Position: %d\n", i);
word_count++;
}
}
}
printf("Word count: %d\n", word_count);
fclose(fp);
return 0;
}
```
该代码首先提示用户输入要查找的单词,然后打开指定的文本文件,逐行读取文件内容并在每行中查找指定单词。如果找到了该单词,就输出包含该单词的句子、单词出现的位置,并统计出现次数。最后输出总共出现的次数。