首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言統計字串中數字、空白與其他字元出現次數:兩種方法對比

     編輯:關於C語言

C 語言統計字串中數字、空白與其他字元出現次數:兩種方法對比

方法一:直接字元比較 (標準 C,無額外相依)

#include <stdio.h>

int main() {
    int num = 0, space = 0, other = 0;
    int ch;
    printf("輸入一行文字: ");
    while ((ch = getchar()) != '\n' && ch != EOF) {
        if (ch >= '0' && ch <= '9') num++;
        else if (ch == ' ') space++;
        else other++;
    }
    printf("數字: %d, 空白: %d, 其他: %d\n", num, space, other);
    return 0;
}

方法二:使用 ctype.h 標準庫函數 (更健壯、可移植)

#include <stdio.h>
#include <ctype.h>

int main() {
    int num = 0, space = 0, other = 0;
    char str[1000];
    printf("輸入字串: ");
    fgets(str, sizeof(str), stdin); // 含換行

    for (char *p = str; *p; ++p) {
        if (isdigit(*p)) num++;
        else if (isspace(*p)) space++; // 涵蓋空格、定位鍵、換行等
        else other++;
    }
    printf("數字: %d, 空白: %d, 其他: %d\n", num, space, other);
    return 0;
}

差異比較

項目方法一方法二
空白判斷僅空格 ' '所有空白字元 (isspace)
輸入方式逐字元 getchar整行 fgets
跨平台ASCII 相容即可標準 C,支援多國字元集
程式碼長度較短稍長

建議

教學初期可用方法一理解 ASCII 碼邏輯;實務專案強烈建議方法二,利用標準庫處理地區設定與特殊空白字元。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved