【經典100題】題目17 輸入一個字串,分別統計出其中的英文字母,空格,陣列,和其他字元的數量。
阿新 • • 發佈:2018-12-22
C語言實現
#include<stdio.h> void main() { int abc = 0; int num = 0; int space = 0; int other = 0; char str; printf("請輸入要統計的字串"); while ((str=getchar())!='\n') { if ((str >= 'a'&&str <= 'z') || str >= 'A'&&str <= 'Z') abc++; else if (str == ' ') space++; else if (str >= '0'&&str <= '9') num++; else other++; } printf("字母的數量:%d\n",abc); printf("數字的數量:%d\n", num); printf("空格的數量:%d\n", space); printf("其他:%d\n", other); }
執行結果:
請輸入要統計的字串the num 520 means I Love You @young people
字母的數量:30
數字的數量:3
空格的數量:8
其他:1
請按任意鍵繼續. . .
python語言實現
str1 = str(input("請輸入要統計的字串:")) abc = 0 num = 0 space = 0 other = 0 for i in range(0,len(str1)): if str1[i] >="a" and str1[i] <= "z": abc+=1 elif str1[i] >="A" and str1[i] <= "Z": abc+=1 elif str1[i] >="0" and str1[i] <= "9": num+=1 elif str1[i] == ' ': space+=1 else: other+=1 print("英文字母:%d"% abc) print("數字:%d"% num) print("空格:%d"% space) print("其他:%d"% other) ''' 將ASCII字元轉換為對應的數值即‘a’-->65,使用ord函式,ord('a') 反正,使用chr函式,將數值轉換為對應的ASCII字元,chr(65) '''
執行結果:
請輸入要統計的字串:the num 520 means I Love You @young people
英文字母:30
數字:3
空格:8
其他:1
★finished by songpl,2018.12.19