練習3-4 統計字符 (15 分)
本題要求編寫程序,輸入10個字符,統計其中英文字母、空格或回車、數字字符和其他字符的個數。
輸入格式:
輸入為10個字符。最后一個回車表示輸入結束,不算在內。
輸出格式:
在一行內按照
letter = 英文字母個數, blank = 空格或回車個數, digit = 數字字符個數, other = 其他字符個數
的格式輸出。
輸入樣例:
aZ &
09 Az
輸出樣例:
letter = 4, blank = 3, digit = 2, other = 1
思路:根據ASCII碼確定統計各類的范圍。
char ch;
數字范圍:0~9 (ch>=48&&ch<=57) 或 (ch>='0'&&ch<='9')
小寫字母:a~z (ch>=97&&ch<=122)或 (ch>='a'&&ch<='z')
大寫字母:A~Z (ch>=65&&ch<=90) 或 (ch>='A'&&ch<='Z')
空格:space (ch==32) 或 (ch==' ')
回車:enter (ch==10) 或 (ch=='\n')
附ASCII碼表:

代碼如下:
#include<stdio.h>
int main()
{
int i, letter, digit, other, blank;
char ch;
digit=0,letter=0,other=0;
for(i=0;i<10;i++)
{
ch=getchar();
if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
letter++;
else if(ch>='0'&&ch<='9')
digit++;
else if(ch==' '||ch=='\n')
blank++;
else
other++;
}
printf("letter = %d, blank = %d, digit = %d, other = %d",letter,blank,digit,other);
return 0;
}
