一、题目
输入一个字符,判断字符是英文,空格还是其他类型。
如图:
二、思路分析
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[],因为整个计算过程都要用到,所以不能是局部变量
关注我 ,每天分享编程知识