Kodewick
開始學 →
基礎←→0 / 50

統計字母、空格、數字個數

#029基礎c >= '0' && c <= '9'約 7 分鐘

補全 count(s):數一數字串裡英文字母(大小寫都算)、空格、數字和其他字元各有幾個,按這個順序顯示四個數。比如 "abc XYZ 2024 #1!":字母 6 個、空格 3 個、數字 5 個、其他 2 個(# 和 !),顯示 6 3 5 2。程式會數兩串。

應該顯示
6 3 5 2
2 6 3 4
main.c
#include <stdio.h>

void count(const char *s) {
    int letters = 0, spaces = 0, digits = 0, others = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        char c = s[i];
        // 在這裡寫:看 c 是哪一類,給對應的計數加 1
    }
    printf("%d %d %d %d\n", letters, spaces, digits, others);
}

int main(void) {
    count("abc XYZ 2024 #1!");
    count("x = 3 * y + 42;");
    return 0;
}
Ctrl + Enter 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。