题目描述:
计算英文文章中各个字母出现的次数?
体会:
1.数组下标可以通过"字符-‘A’"的方式来确定。
2.不像python键值对那么方便,数组下标只能是数字,可以通过建立结构体的方式达到将字母和字母出现次数结合起来的目的。
代码:
//计算英文文章中各个字母出现的次数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct {
char alph;
int count;
}alph[26];
void read();
void print();
int main(){
read();
print();
return 0;
}
void read(){
int count[26]={0};
FILE *fp;
char store;
int i;
if((fp=fopen("D:\\2019Post\\pat\\pat\\data.txt","r"))==NULL){
printf("can not open the file");
exit(0);
}
while(!feof(fp)){
store=fgetc(fp);
if(store>='a'&&store<='z'){
count[store-'a']++;
}
else if(store>='A'&&store<='Z'){
count[store-'A']++;
}
}
for(i=0;i<26;i++){
alph[i].alph='A'+i;
alph[i].count=count[i];
}
}
void print(){
int i;
for(i=0;i<26;i++){
printf("字母%c出现%d次\n",alph[i].alph,alph[i].count);
}
}