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

C語言字符分類:判斷字母、數字與其他字符的標準方法

     編輯:C 語言問答

需求

輸入一個字符,判斷其屬於:英文字母、數字字符、其他字符。

標準庫方案(推薦)

#include <stdio.h>
#include <ctype.h>  // 提供 isalpha, isdigit 等

int main() {
    char ch;
    printf("請輸入一個字符: ");
    scanf(" %c", &ch);  // 格式串前空格跳過空白/換行

    if (isalpha(ch)) {
        printf("'%c' 是英文字母\n", ch);
    } else if (isdigit(ch)) {
        printf("'%c' 是數字字符\n", ch);
    } else {
        printf("'%c' 是其他字符\n", ch);
    }
    return 0;
}

ctype.h 核心分類函數速查

函數判斷條件備註
isalpha(c)字母 (A-Z, a-z)區分大小寫
isupper(c)大寫字母 (A-Z)
islower(c)小寫字母 (a-z)
isdigit(c)數字字符 (0-9)
isalnum(c)字母或數字isalpha||isdigit
isspace(c)空白字符 (空格、\n、\t、\v、\f、\r)
ispunct(c)標點符號 (非字母數字、非空白的可打印字符)
isprint(c)可打印字符 (含空格)
iscntrl(c)控制字符 (ASCII 0-31, 127)
isxdigit(c)十六進制數字 (0-9, A-F, a-f)

手動 ASCII 碼判斷(無庫版本)

// 僅適用 ASCII 兼容字符集
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
    puts("字母");
else if (ch >= '0' && ch <= '9')
    puts("數字");
else
    puts("其他");

⚠️ **缺點**:不支援 EBCDIC 等非 ASCII 字符集,可移植性差。**生產代碼務必用 ctype.h**。

常見錯誤避坑

  1. 條件寫錯:if (ch >= 'a' && ch <= 'z' || ch >= 'a' && ch <= 'z') 重複判斷小寫,漏掉大寫。正確應包含兩段範圍。
  2. scanf 不加空格:scanf("%c", &ch) 會讀到上一輪殘留的 \n,導致誤判為「其他」。**必須 scanf(" %c", &ch)**。
  3. 參數類型:ctype.h 函數參數為 int,但傳 char 會自動提升,無需轉換。若 char 為有符號且負值,需轉 unsigned char 避免 UB:isalpha((unsigned char)ch)。

進階:統計字符串中各類字符數量

void analyze(const char *s) {
    int alpha=0, digit=0, other=0;
    for (; *s; s++) {
        if (isalpha(*s)) alpha++;
        else if (isdigit(*s)) digit++;
        else other++;
    }
    printf("字母:%d 數字:%d 其他:%d\n", alpha, digit, other);
}

總結

  • **首選 ctype.h**:isalpha/isdigit 標準、可移植、區域感知(配合 setlocale)。
  • scanf(" %c", &ch) 格式串前空格**必加**,跳過空白字符。
  • 手動 ASCII 判斷僅限教學/極受限環境,生產禁用。
  • 擴展到字符串統計只需一層迴圈,同理可做詞頻、密碼強度檢查等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved