有一篇文章,共有3行文字,每行有80個字符。要求分別統計出其中英文大寫字母、小寫字母、數字、空格以及其他字符的個數
【答案解析】
獲取文章中的3行文本,並對每行文本進行以下操作
- 定義保存結果變量:upp、low、digit、space、other
- 遍歷每行文本中的字符
- 如果該字符ch:ch >= 'a' && ch <='z',則該字符是小寫字母,給low++
- 如果該字符ch:ch >= 'A' && ch <='Z',則該字符是小寫字母,給up++
- 如果該字符ch:ch >= '0' && ch <='9',則該字符是小寫字母,給digit++
- 如果該字符ch:ch == ' ',則該字符是小寫字母,給space++
- 否則為其他字符,給other++
輸入統計結果
【代碼實現】
#include <stdio.h>
int main()
{
int upp = 0, low = 0, digit = 0, space = 0, other = 0;
char text[3][80];
for (int i=0; i<3; i++)
{
// 獲取一行文本
printf("please input line %d:\n",i+1);
gets(text[i]);
// 統計該行文本中小寫字母、大寫字母、數字、空格、其他字符的個數
for (int j=0; j<80 && text[i][j]!='\0'; j++)
{
if (text[i][j]>='A'&& text[i][j]<='Z') // 大寫字母
upp++;
else if (text[i][j]>='a' && text[i][j]<='z') // 小寫字母
low++;
else if (text[i][j]>='0' && text[i][j]<='9') // 數字
digit++;
else if (text[i][j]==' ') // 控制
space++;
else
other++; // 其他字符
}
}
printf("\nupper case: %d\n", upp);
printf("lower case: %d\n", low);
printf("digit : %d\n", digit);
printf("space : %d\n", space);
printf("other : %d\n", other);
return 0;
}
【結果截屏】