如何用C语言统计字符串中的数字,字符,空格和其他字符的个数,
#include<stdio.h>
#include<string.h>
int main()
{
int s = 0, l = 0, o = 0, n = 0;
int i;
char arr[50];
memset(arr, 0, sizeof(char) * 50);
scanf("%[^\n]", &arr);//以回车结尾
for (i = 0; i < 50; i++)
{
if (arr[i] == '\0')
break;
else if (arr[i] == 32)
s++;
else if ( (arr[i] > 64 && arr[i] < 91) || (arr[i] > 96 && arr[i] < 123) )//大小写字符
l++;
else if (arr[i] > 47 && arr[i] < 58)
n++;
else o++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n", l, s, n, o);
return 0;
}
望采纳 ,谢谢!!
#include<stdio.h>
int main()
{
int digit, other, blank;
char ch;
digit=0,blank=0,other=0;
//首先定义计数变量并初始化
while((ch=getchar())!='\n')
{ //当输入不等于回车时循环
//根据各种情况用if语句判断来设置变量的值
if(ch>='0'&&ch<='9')
digit++;
else if(ch==' ')
blank++;
else
other++;
} //最后按照题目给出的格式进行打印输出
printf("blank = %d, digit = %d, other = %d\n",blank,digit,other);
return 0;
}