栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现文件字符串的查找和按出现次数排序

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言实现文件字符串的查找和按出现次数排序

#pragma warning(disable:4996) 
#include
#include
#include

typedef struct {
	char str[50]; //单词最大长度设为50
	int cnt;//单词出现次数
}Str;

int main() {
	char tmp[50];
	FILE* fp;
	Str words[200]; //单词数量上限 
	int num = 0;//实际单词数量 
	int i, j, neww = 1;//neww标志位,判断是否为新单词 
	fp = fopen("test.txt", "r");
	//fscanf从文件中获取单个字符串 
	while (fscanf(fp, "%s", tmp) != EOF) {
		neww = 1;
		for (i = 0; i < num; i++) {
			//重复的单词 
			if (strcmp(tmp, words[i].str) == 0) {
				neww = 0;
				words[i].cnt++;
			}
		}
		if (neww) {
			// 复制字符串
			for (j = 0; tmp[j] != ''; j++) {
				words[num].str[j] = tmp[j];
			}
			//单词末尾添加结束符 
			words[num].str[j] = '';
			// 新单词数量+1 
			words[num++].cnt = 1;
		}
	}
	printf("一共%d个不同的单词,每个单词出现次数如下:n", num);
	for (i = 0; i <= num - 1; i++) {
	//打印10位以内的字符串
		printf("%-10s %2dn", words[i].str, words[i].cnt);
	}
	fclose(fp);
	return 0;
}

> ```因为我使用的是VS2019,VS要求文件读取使用fopen_s,fclose_s 引用#pragma
> warning(disable:4996) 可以解决这个版本问题`~~~ 
![在这里插入图片描述](https://img-blog.csdnimg.cn/0cfc1d5ecc784fefa64da12b7f40c325.png#pic_center)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1018952.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号