当前位置:网站首页>统计文本中字母的频次(不区分大小写)

统计文本中字母的频次(不区分大小写)

2020-11-07 20:19:13 PamShao

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 10240

void count(char* n)
{
	int i = 0, s[26] = { 0 };
	while (n[i] != NULL)
	{
		if (n[i] >= 'A' && n[i] <= 'Z')
		{
			n[i] += 32;
			s[n[i] - 'a']++;
			i++;
		}
		else if (n[i] >= 'a' && n[i] <= 'z')
		{
			s[n[i] - 'a']++;
			i++;
		}
		else
			i++;
	}

	for (i = 0; i < 26; i++)
	{
		printf("%c出现:%d次\n", (char)(i + 'a'), s[i]);
	}
}
int main() {
	char buf[MAX_NUM];			//字符缓冲区
	FILE* fp;
	//fopen("doc.txt", "r+"),读取文本中的内容
	if ((fp = fopen("doc.txt", "r+")) == NULL) {
		perror("the file fail to read");
		exit(1);
	}
	while (!feof(fp) && !ferror(fp)) {	//文件读取结束或出错则退出
   //while(fgets(buf,MAX_NUM,fp) != NULL)
		fgets(buf, MAX_NUM, fp);//每次读取一行或者MAX_NUM个字符
		printf("内容为:%s \n", buf);
		count(buf);
	}
	fclose(fp);				//关闭文件
	return 0;
}

 

版权声明
本文为[PamShao]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/pam-sh/p/13941989.html