ctype.h 介紹

標頭檔案 ctype.h 是標準 C 庫的一部分。它提供了分類和轉換字元的功能。

所有這些函式都有一個引數,一個必須是 EOF 或者可以表示為 unsigned char 的 int

分類函式的名稱以 is 為字首。如果傳遞給它的字元滿足相關條件,則每個返回一個整數非零值(TRUE)。如果條件不滿足,則函式返回零值(FALSE)。

假設預設的 C 語言環境,這些分類函式如圖所示執行:

int a;
int c = 'A';
a = isalpha(c); /* Checks if c is alphabetic (A-Z, a-z), returns non-zero here. */
a = isalnum(c); /* Checks if c  is alphanumeric (A-Z, a-z, 0-9), returns non-zero here. */
a = iscntrl(c); /* Checks is c is a control character (0x00-0x1F, 0x7F), returns zero here. */
a = isdigit(c); /* Checks if c is a digit (0-9), returns zero here. */
a = isgraph(c); /* Checks if c has a graphical representation (any printing character except space), returns non-zero here. */
a = islower(c); /* Checks if c is a lower-case letter (a-z), returns zero here. */
a = isprint(c); /* Checks if c is any printable character (including space), returns non-zero here. */
a = isupper(c); /* Checks if c is a upper-case letter (a-z), returns zero here. */
a = ispunct(c); /* Checks if c is a punctuation character, returns zero here. */
a = isspace(c); /* Checks if c is a white-space character, returns zero here. */
a = isupper(c); /* Checks if c is an upper-case letter (A-Z), returns non-zero here. */
a = isxdigit(c); /* Checks if c is a hexadecimal digit (A-F, a-f, 0-9), returns non-zero here. */

Version >= C99

a = isblank(c); /* Checks if c is a blank character (space or tab), returns non-zero here. */

有兩種轉換功能。這些是使用字首’to’命名的。這些函式採用與上述相同的引數。但是,返回值不是簡單的零或非零,但傳遞的引數以某種方式更改。

假設預設的 C 語言環境,這些轉換函式如圖所示執行:

int a;
int c = 'A';

/* Converts c to a lower-case letter (a-z). 
 * If conversion is not possible the unchanged value is returned. 
 * Returns 'a' here. 
 */
a = tolower(c);

/* Converts c to an upper-case letter (A-Z). 
 * If conversion is not possible the unchanged value is returned. 
 * Returns 'A' here. 
 */
a = toupper(c);

以下資訊引自 cplusplus.com 對映每個分類型別函式如何考慮原始 127 個字元的 ASCII 集(a•表示該函式對該字元返回非零值)

ASCII 值 字元 iscntrl 判斷 ISBLANK isspace 為 isupper islower 判斷 因而 isalpha ISDIGIT isxdigit 判斷 字元 isalnum ispunct 判斷 isgraph isprint 判斷
0x00 .. 0x08 NUL,(其他控制程式碼)
×09 標籤(’\ t’)
0x0A .. 0x0D (空格控制程式碼:’\ f’,’\ v’,’\ n’,’\ r’)
0x0E .. 0x1F (其他控制程式碼)
為 0x20 空間 (’ ‘)
0x21 .. 0x2F !“#$%&’()* +, - 。/
0x30 .. 0x39 0123456789
0x3a .. 0x40 :; <=> @
0x41 .. 0x46 ABCDEF
0x47 .. 0x5A GHIJKLMNOPQRSTUVWXYZ
0x5B .. 0x60 [] ^ _`
0x61 .. 0x66 ABCDEF
0x67 .. 0x7A ghijklmnopqrstuvwxyz
0x7B .. 0x7E {}〜bar
0x7F (DEL)