统计字符个数

问题描述:

输入一行字符,统计其中的英文字母,空格,数字和其他字符的个数。

算法分析:

用函数判定字符类型,再使用变量累加。但这里输入不要用scanf()函数,因为它遇到空格就终止读入字符,改用getchar()函数。

代码如下:

View Code
 1 #include <stdio.h>
2 #include <ctype.h>
3
4 int main(void)
5 {
6 char c;
7 int character = 0; // 字母
8 int num = 0; // 数字
9 int space = 0; // 空格
10 int s_char = 0; // 特殊字符
11
12
13 while((c=getchar())!='\n')
14 {
15 if(isalpha(c))
16 character++;
17 else if(isdigit(c))
18 num++;
19 else if(isspace(c))
20 space++;
21 else
22 s_char++;
23 }
24
25 printf("%d %d %d %d", character, num, space, s_char);
26
27 return 0;
28 }

输出结果:

hello world! 123
10 3 2 1

posted @ 2011-10-14 10:39  jeff_nie  阅读(213)  评论(0编辑  收藏  举报