萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ <cctype> 字符分類與轉換函數速查表與實戰範例

函數速查表

函數判斷/轉換條件返回值
isalnum(c)字母或數字非零(true)/零(false)
isalpha(c)字母 (A-Z, a-z)非零/零
iscntrl(c)控制字符 (0x00-0x1F, 0x7F)非零/零
isdigit(c)十進制數字 (0-9)非零/零
isgraph(c)可打印非空格字符非零/零
islower(c)小寫字母非零/零
isprint(c)可打印字符(含空格)非零/零
ispunct(c)標點符號非零/零
isspace(c)空白字符 (空格、\t、\n、\v、\f、\r)非零/零
isupper(c)大寫字母非零/零
isxdigit(c)十六進制數字 (0-9, A-F, a-f)非零/零
tolower(c)大寫→小寫,否則原樣int (ASCII 碼)
toupper(c)小寫→大寫,否則原樣int (ASCII 碼)

關鍵注意事項

  • 所有函數參數為 int,但值必須在 unsigned char 範圍 (0-255) 或 EOF,否則行為未定義(負數 char 直接傳入是常見 Bug)。
  • 轉換函數返回 int,需 static_cast<char>(tolower(c)) 或賦值給 char 變數。
  • 行為受當前 locale 影響(如德語 ß、土耳其語 İ),嚴格 ASCII 場景可用 std::ctype<char> 或查表法。

實戰範例

1. 統計字符串中各類字符數量

#include <iostream>
#include <cctype>
#include <string>

void analyze(const std::string& s) {
    int alpha=0, digit=0, space=0, punct=0, other=0;
    for (unsigned char ch : s) {
        if (std::isalpha(ch)) ++alpha;
        else if (std::isdigit(ch)) ++digit;
        else if (std::isspace(ch)) ++space;
        else if (std::ispunct(ch)) ++punct;
        else ++other;
    }
    std::cout << "字母:" << alpha << " 數字:" << digit
              << " 空白:" << space << " 標點:" << punct << " 其他:" << other << '\n';
}

2. 大小寫轉換與標準化

std::string toLower(const std::string& s) {
    std::string r; r.reserve(s.size());
    for (unsigned char ch : s) r.push_back(static_cast<char>(std::tolower(ch)));
    return r;
}

// 去除首尾空白
std::string trim(const std::string& s) {
    size_t i = 0, j = s.size();
    while (i < j && std::isspace(static_cast<unsigned char>(s[i]))) ++i;
    while (j > i && std::isspace(static_cast<unsigned char>(s[j-1]))) --j;
    return s.substr(i, j-i);
}

3. 輸入驗證:只允許字母數字下劃線

bool isValidIdentifier(const std::string& s) {
    if (s.empty()) return false;
    if (!std::isalpha(static_cast<unsigned char>(s[0])) && s[0] != '_') return false;
    for (size_t i = 1; i < s.size(); ++i) {
        unsigned char ch = s[i];
        if (!std::isalnum(ch) && ch != '_') return false;
    }
    return true;
}

現代 C++ 替代方案

  • <charconv> (C++17) 高性能數值解析,不依賴 locale。
  • std::ranges::all_of + lambda 表達式更聲明式。
  • Unicode 完整支援請使用 Boost.Locale 或 ICU。
copyright © 萬盛學電腦網 all rights reserved