
上QQ阅读APP看书,第一时间看更新
8.5.1 字符检测函数
字符检测函数可对程序中的字符进行检测处理,这些函数根据字符是否满足特定的条件来返回true或false。C语言中的字符检测函数通过头文件“ctype.h”来引用,常用的字符检测函数如表8-2所示。
表8-2 常用的字符检测函数

实例8-12
提示用户输入一段字符串,然后使用字符检测函数来判断字符串中各字符的个数
源码路径daima\8\8-12
拓展范例及视频二维码
范例8-12-01:删除多个连续的字符串
源码路径:演练范例\8-12-01\

范例8-12-02:字符串的升序排序
源码路径:演练范例\8-12-02\

本实例的实现文件为“num.c”,具体实现代码如下。
#include "stdafx.h" #include "string.h" #include "stdio.h" #include "ctype.h" int main(void) { char mm[80]; //定义一个字符数组 int i, d = 0, l = 0, p = 0, c = 0, o = 0, b = 0, u = 0; //定义整型变量 printf("Please input the string:\n"); gets_s(mm); //输入字符串 for (i = 0; i<strlen(mm); i++)//循环检测字符串中的每个字符 { if (isprint(mm[i]))//判断当前字符是否为可打印字符 { if (isalnum(mm[i]))//判断当前字符是否为字母或数字 { //判断当前字符是否为数字 if (isdigit(mm[i])) d++; //判断当前字符是否为小写字母 else if (islower(mm[i])) l++; //判断当前字符是否为大写字母 else if (isupper(mm[i])) u++; } else if (isspace(mm[i]))//判断当前字符是否为空格 b++; else if (ispunct(mm[i]))//判断当前字符是否为标点字符 p++; else o++; } else if (iscntrl(mm[i]))////判断当前字符是否为控制字符 c++; else //以上类型都不是 o++; } //输出字符串中各种类型字符的个数 printf("数字:%d\n", d); printf("小写字母:%d\n", l); printf("大写字母:%d\n", u); printf("空白:%d\n", b); printf("标点符号:%d\n", p); printf("控制键:%d\n", c); printf("其他:%d\n", o); }
程序运行后先提示用户输入字符串,输入完毕并按下Enter键后会显示字符检测函数的处理结果。执行效果如图8-12所示。

图8-12 执行效果