c语言:判断字符类型|练习题
一、题目
 输入一个字符,判断字符是英文,空格还是其他类型。
 如图:

?
二、思路分析
 1、输入一串字符,以回车键结束
 2、每输入一个字符时,判断该字符的类型
 3、统计各类型字符的个数
三、代码截图【带注释】

?
四、源代码【带注释】
#include <stdio.h>
 #define maxLen 999
 int strLen=0;
 char str[0];
//判断字符是数字、空格,还是其他,并统计
 icondetermineCharType(char str[],int strLen)
 {
 ? ? int charCount=1;
 ? ? int spaceCount=0;
? ? //因为最后有一个0/算进了其他那里,所以要-1
 ? ? int otherCount=-1;
? ? //判断并统计
 ? ? for(int i=0; i<strLen; i++)
 ? ? {
 ? ? ? ? //判断是否是字符
 ? ? ? ? if(isalpha(str[i]))
 ? ? ? ? {
 ? ? ? ? ? ? charCount++;
 ? ? ? ? }
 ? ? ? ? //判断是否是空格
 ? ? ? ? else if(isspace(str[i]))
 ? ? ? ? {
 ? ? ? ? ? ? spaceCount++;
 ? ? ? ? }
 ? ? ? ? //判断是否是其他
 ? ? ? ? else
 ? ? ? ? {
 ? ? ? ? ? ? otherCount++;
 ? ? ? ? }
 ? ? }
 ? ? printf("\n统计结果:\n字符数=%d 空格数=%d 其他=%d",
 ? ? ? ? ? ?charCount,spaceCount,otherCount);
 }
int main()
 {
 ? ? printf("请输入一串字符:");
 ? ? //作用:输入字符,当按下回车时,输入结束
 ? ? do
 ? ? {
 ? ? ? ? strLen++;//记录字符串长度
 ? ? ? ? scanf("%c",&str[strLen]);//输入字符串
 ? ? }
 ? ? while(str[strLen]!='\n');
 ? ? //当等于回车时,输入结束
? ? strLen=strLen-1;//因为最后有一个/0,所以要减1
 ? ? printf("字符串长度为:%d",strLen);
? ? //调用函数
 ? ? determineCharType(str,strLen);
 }
五、运行结果

?
六、注意
 1、 变量strLen和str[],因为整个计算过程都要用到,所以不能是局部变量
?
关注我?,每天分享编程知识
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!