(从键盘输入若干字符,直到按回车键结束。分别统计字母字符、数字字符和其他字符的个数)大一新生
供参考:
#include <stdio.h>
#include <string.h>
int main()
{
char c;
int letter = 0, digit = 0, other = 0;
printf("请输入一行字符:\n");
while ((c = getchar()) != '\n')
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
letter++;
}
else if (c >= '0' && c <= '9')
{
digit++;
}
else {
other++;
}
}
printf("字母有:%d个,数字有:%d个,其他字符有:%d个\n", letter, digit, other);
return 0;
}
#include<stdio.h>
int main(){
char a[1024];
int cnt_upper = 0, cnt_lower = 0, cnt_chinese = 0, cnt_digit = 0, cnt_space = 0, cnt_others = 0;
gets(a);
for ( int j = 0; j < strlen(a); j++ )
{
if ( a[j] >= 'a' && a[j] <= 'z' )
cnt_lower++;
else if ( a[j] >= 'A' && a[j] <= 'Z' )
cnt_upper++;
else if ( a[j] >= '0' && a[j] <= '9' )
cnt_digit++;
else if ( a[j] == ' ' )
cnt_space++;
else if ( a[j] < 0 )
{
cnt_chinese++, j++;
}else cnt_others++;
}
printf( "upper:%d\nlower:%d\nchinese:%d\ndigit:%d\nspace:%d\nothers:%d\n", cnt_upper, cnt_lower, cnt_chinese, cnt_digit, cnt_space, cnt_others );
return 0;
}
运行结果: