c语言 不同单词出现次数,怎样用c语言编写某个文本文件中不同单词出现的次数...

d3211d2a4bd072692dab716d10bbb5dc.png

#include <stdio.h>

int fun(int a[], int n, int b[], int m, int c[])

{

int i = 0, j = m - 1, k = 0;

while(i < n && j >= 0)

c[k++] = a[i] < b[j] ? a[i++] : b[j--];

while(i < n)

c[k++] = a[i++];

while(j >= 0)

c[k++] = b[j--];

return k;

}

int main()

{

int a[5] = {1, 4, 7, 11, 12}, b[5] = {15, 13, 10, 6, 5}, c[20];

int i, n;

printf("数组a的元素:\n");

for(i = 0; i < 5; i++)

printf("%d ", a[i]);

printf("\n");

printf("数组b的元素:\n");

for(i = 0; i < 5; i++)

printf("%d ", b[i]);

printf("\n");

n = fun(a, 5, b, 5, c);

printf("合并后数组c的元素:\n");

for(i = 0; i < n; i++)

printf("%d ", c[i]);

return 0;

}

#include <stdio.h></p><p>int fun(int a[], int n, int b[], int m, int c[])</p><p>{</p><p>int i = 0, j = m - 1, k = 0;</p><p>while(i < n && j >= 0)</p><p>c[k++] = a[i] < b[j] ? a[i++] : b[j--];</p><p>while(i < n)</p><p>c[k++] = a[i++];</p><p>while(j >= 0)</p><p>c[k++] = b[j--];</p><p>return k;</p><p>}</p><p>int main()</p><p>{</p><p>int a[5] = {1, 4, 7, 11, 12}, b[5] = {15, 13, 10, 6, 5}, c[20];</p><p>◆◆</p><p>评论读取中....</p><p>请登录后再发表评论!</p><p>◆◆</p><p>修改失败,请稍后尝试</p></div>

编写一个C语言程序来统计文本文件每个单词出现次数,可以分为以下几个步骤: 1. 打开文件:首先需要打开指定的文本文件,通常使用`fopen()`函数。 ```c #include <stdio.h> FILE *file = fopen("filename.txt", "r"); if (file == NULL) { printf("Failed to open file.\n"); return; } ``` 2. 读取文件内容:通过`fgets()`逐行读取文件内容,并将每行分割成单词数组。 ```c char line[1000]; while (fgets(line, sizeof(line), file)) { // 分割单词 char *word = strtok(line, " "); while (word != NULL) { // 统计单词 // ... word = strtok(NULL, " "); } } ``` 3. 计数和存储:创建一个结构体或哈希表来保存每个单词及其对应的计数。这里我们可以使用`struct WordCount` 或者 `std::map<char*, int>` 来记录。 ```c #include <ctype.h> // 对于tolower() 函数 typedef struct { char* word; int count; } WordCount; WordCount word_counts[MAX_WORDS]; // 根据实际需求设置MAX_WORDS大小 int count_index = 0; // 更新计数 void update_count(char* word) { word = tolower(word); // 转换为小写便于比较 for (int i = 0; i < count_index; i++) { if (!strcmp(word, word_counts[i].word)) { word_counts[i].count++; break; } } if (i == count_index) { word_counts[count_index].word = strdup(word); word_counts[count_index].count = 1; count_index++; } } ``` 4. 关闭文件:完成所有处理后,记得关闭文件。 ```c fclose(file); ``` 5. 输出结果:遍历结构体,打印每个单词及其出现次数。 ```c for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } ``` 完整的代码示例如下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORDS 1000 ... void main() { // 省略打开、读取文件和更新计数部分... // 输出结果 for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } // 省略关闭文件部分... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值