统计每个字符的出现次数(C语言)
统计每个字符的出现次数(C语言)
输入包含字母和数字,要求统计每个字符的出现次数
输入:AsdaAffid333778
输出:a:3
d:2
f:2
i:1
s:1
3:3
7:2
8:1
注意:输入是从文件中读入,输出是写入文件中
#include <stdio.h>
#include <ctype.h>
int main()
{
FILE *fp;
int i,a[36]={ 0};//a用来统计字符个数
char ch;
if((fp=fopen("F:\\string.txt","r")) == NULL)
{
printf("cannot open the file\n");
return 0;
}
while((ch=fgetc(fp)) != EOF)
{
if(isdigit(ch))
a[ch-'0'+26]++;
else if(isalpha(ch))
a[tolower(ch)-'a']++;
}
fclose(fp);
if((fp=fopen("F:\\word.txt","w")) == NULL)
{
printf("cannot open the file\n");
return 0;
}
for(i=0; i<36; i++)
{
if(a[i])
{
ch=i<26?i+'a':i-26+'0';
fprintf(fp,"%c:%d\n",ch,a[i]);
}
}
fclose(fp);
return 0;
}
还没有评论,来说两句吧...