輸入一行文字,找出其中大寫字母、小寫字母、空格、數字以及其他字元各有多少
阿新 • • 發佈:2020-07-27
輸入一行文字,找出其中大寫字母、小寫字母、空格、數字以及其他字元各有多少
解題思路: 字元可以直接進行比較,但是要注意字串中的數字是字元數字,必須以字元的形式比較,也就是加上單引號
答案:
#include <stdio.h> #include <string.h> int main() { char buf[1024]; printf("Please enter a string: "); gets_s(buf, 1024); int upper_count = 0, lower_count = 0, digit_count = 0, space_count = 0, other_count = 0; char *ptr = buf; while (*ptr != '\0') { if (*ptr >= 'A' && *ptr <= 'Z') { //大寫字母 upper_count++; }else if (*ptr >= 'a' && *ptr <= 'z'){//小寫字母 lower_count++; }else if (*ptr >= '0' && *ptr <= '9') {//數字字元 digit_count++; }else if (*ptr== ' ') {//空格字元 space_count++; }else { //其他字元 other_count++; } ptr++; } printf("upper:%d; lower:%d; digit:%d; space:%d; other:%d\n", \ upper_count, lower_count, digit_count, space_count, other_count); system("pause"); return 0; }