有一篇文章,共有3行文字,每行有80個字元。要求分別統計出其中英文大寫字母、小寫字母、數字、空格以及其他字元的個數
阿新 • • 發佈:2020-08-03
有一篇文章,共有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; }
【結果截圖】