目標(biāo):
輸入一行字符,統(tǒng)計(jì)其中各種字符的個(gè)數(shù)。
具體代碼:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define M 1024 void main() { char str[M]; fgets(str, M, stdin); int space = 0; int letter = 0; int num = 0; int other = 0; for (int i = 0; i < (int)strlen(str); ++i) { if (str[i] == ' ') { space += 1; } else if (str[i] > 64 && str[i] < 91 || str[i]>96 && str[i] < 123) { letter += 1; } else if (str[i] > 47 && str[i] < 58) { num += 1; } else { if (str[i] != 'n') {//因?yàn)閒gets()函數(shù)會(huì)在末尾自動(dòng)加上n,影響判斷結(jié)果,需要判斷是否為換行符 other += 1; } } } printf("空格的個(gè)數(shù)為:%dn", space); printf("英文字母的個(gè)數(shù)為:%dn", letter); printf("數(shù)字的個(gè)數(shù)為:%dn", num); printf("其他字符的個(gè)數(shù)為:%dn", other); system("pause"); }
注意:fgets()函數(shù)會(huì)在字符串末尾(