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

C語言統計字符串中字母、數字、空格及其他字符個數:完整代碼實現

     編輯:C 語言問答

需求

輸入一行字符,分別統計英文字母、空格、數字、其他字符的個數。

標準庫函數法(推薦)

#include <stdio.h>
#include <ctype.h> // isalpha, isdigit, isspace

int main(void) {
    char line[1024];
    printf("請輸入一行字符: ");
    if (!fgets(line, sizeof(line), stdin)) return 0;

    int letters = 0, digits = 0, spaces = 0, others = 0;
    for (char *p = line; *p; ++p) {
        if (isalpha((unsigned char)*p)) letters++;
        else if (isdigit((unsigned char)*p)) digits++;
        else if (isspace((unsigned char)*p)) spaces++;
        else others++;
    }
    printf("字母: %d, 數字: %d, 空格: %d, 其他: %d\n",
           letters, digits, spaces, others);
    return 0;
}

手動判斷法(不依賴 ctype.h)


for (char *p = line; *p; ++p) {
    char ch = *p;
    if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) letters++;
    else if (ch >= '0' && ch <= '9') digits++;
    else if (ch == ' ' || ch == '\t' || ch == '\n') spaces++;
    else others++;
}

關鍵點

  • 輸入處理:用 fgets 讀整行,保留空格、制表符;scanf("%s") 會跳過空白,不適用。
  • 字符分類:ctype.h 函數要求參數為 unsigned char 或 EOF,故轉換 (unsigned char)*p 避免負值未定義行為。
  • 換行符:fgets 會保留末尾 \n,統計空白時包含它;若不想算,可在循環前 line[strcspn(line, "\n")] = 0; 去除。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved