C语言统计字符串中各个小写字母出现的次数

作为计算机科学与技术专业的一名大一学生,这是我第一次写博客
主要是谈一下一道统计字符个数的C语言题目
题目来源是 《杭州电子科技大学第三届程序设计大赛》

题目原型
Ignatius is doing his homework now. The teacher gives him some articles and asks him to tell how many times each letter appears.

It’s really easy, isn’t it? So come on and AC ME.
Input
Each article consists of just one line, and all the letters are in lowercase. You just have to count the number of each letter, so do not pay attention to other characters. The length of article is at most 100000. Process to the end of file.

Note: the problem has multi-cases, and you may use “while(gets(buf)){…}” to process to the end of file.
Output
For each article, you have to tell how many times each letter appears. The output format is like “X:N”.

Output a blank line after each test case. More details in sample output.
Sample Input
hello, this is my first acm contest!
work hard for hdu acm.
Sample Output
a:1
b:0
c:2
d:0
e:2
f:1
g:0
h:2
i:3
j:0
k:0
l:2
m:2
n:1
o:2
p:0
q:0
r:1
s:4
t:4
u:0
v:0
w:0
x:0
y:1
z:0

a:2
b:0
c:1
d:2
e:0
f:1
g:0
h:2
i:0
j:0
k:1
l:0
m:1
n:0
o:2
p:0
q:0
r:3
s:0
t:0
u:1
v:0
w:1
x:0
y:0
z:0
题目意思我也就不阐述了,主要原因是所有大型竞赛中比赛题目都采用英文,所以大家平时也应该养成习惯,自己努力翻译,不懂就查找或则询问同学,一定时间后就会得到改善

题目也提示了用while(gets(buf))来控制是否结束问题,当然也可以试着采用EOF的方法,但是基本一样,其次是采用宏定义,题目上说100000以内,一般定义时会在题目基础上加5,所以定义100005、其次是定义两个数组,巧妙的解决字母和对应个数的问题,由于采用了宏定义,所以这里可以采用==’\0’的方式来判定是否应该结束,采用一个条件语句就能解决问题,在数组中这种思想一定要具备,方法简单,但是特别重要,其次就是输出样式,输出样式时重中之重,特别是在网络平台提交时特别重要(特别提示:系统提交是时显示演示文稿错误一类的提示基本是格式错误,主要涉及的两个重要点就是跳行和空格的问题,这个问题我也会在下一篇博客里再次细说,这道题的格式没有要求,主要是一个跳行)其他细小方面就不详细阐述了,以后的博客也会慢慢补足其他各方面的详细问题,欢迎关注
下面是代码,完全是自己写的,所以不是特别精炼,所以希望大家可以学习思路,可以自己动手做一做。

#include<stdio.h>
#include<string.h>
#define m 100005
int main ()
{
char a[26];
int b[26];
char str[m];
int i,j;
for(i=0;i<26;i++)
a[i]=(char)(97+i);
while((gets(str)))
{
for(i=0;i<26;i++)
b[i]=0;
for(i=0;i<=m;i++)
{
if(str[i]==’\0’)
break;
else
for(j=0;j<26;j++)
if(str[i]==a[j])
b[j]++;
}
for(i=0;i<26;i++)
printf("%c:%d\n",a[i],b[i]);
printf("\n");
}
return 0;
}

  • 26
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值