编写一个程序,从标准输入字符,并根据下面分类统计字符个数;
控制字符
空白字符
数字
小写字母
大写字母
标点符号
不可打印字符
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/*判断字符是否可以打印*/
int is_not_printf(int ch)
{
return !isprint(ch);
}
/*用于区别类型的分类函数跳转表,函数大部为系统函数*/
int (*test_func[])(int) =
{
iscntrl,
isspace,
isdigit,
islower,
isupper,
ispunct,
is_not_printf
};
/*定义数组大小,增加通用性*/
#define N_CATE (sizeof(test_func)/sizeof(test_func[0]))
/*定义打印的字符说明*/
char *label[] =
{
"control",
"space",
"digit",
"lower",
"upper",
"punct",
"non-print"
};
int main()
{
int coun[N_CATE]={0,0,0,0,0,0,0};/*偷懒的数组初始化,应该用循环初始以便增加通用性,这里不改了*/
int totol = 0;
int ch;
int categ;
while((ch=getchar()) != EOF)
{
totol += 1;
for(categ = 0;categ < N_CATE;categ +=1)
{
if(test_func[categ](ch))
{
coun[categ] += 1;
break;/*匹配成功则跳出,提高效率*/
}
}
}
for(categ = 0;categ < N_CATE; categ++)
{
printf("%s = %d/n",label[categ],coun[categ]);
}
getchar();
return 0;
}
转移表其实就是函数指针数组,这样使用可以避免使用if,case之类的匹配函数,看着好看点。