ctype.h
外觀

C標準函式庫 |
---|
一般 |
雜項 |
ctype.h
是C標準函數庫中的頭文件,定義了一批C語言字符分類函數(C character classification functions),用於測試字符是否屬於特定的字符類別,如字母字符、控制字符等等。既支持單字節字符,也支持寬字符。[1]
實現
[編輯]現代的C庫中,字符分類函數一般不用比較測試(comparison tests)實現,而是靜態查表來實現。
例如,創建一個由256個8位寬整數組成的數組,每個整數的每位對應字符的特定的分類性質,如屬於數字、屬於字母等等。如果最低位表示屬於數字性質,那麼可以寫成如下代碼:
#define isdigit(x) (TABLE[x] & 1)
早期版本的Linux使用了潛在犯錯的方法,類似於:
#define isdigit(x) ((x) >= '0' && (x) <= '9')
這會產生問題,如宏參數x
具有副作用---例如,如果調用isdigit(x++)
或isdigit(run_some_program())
,可能不是很顯然,isdigit
的參數將被求值兩次。所以,查表的方法被廣泛使用。
函數
[編輯]單字節字符處理函數在ctype.h
(C++的cctype
)中聲明。寬字節字符處理函數在wctype.h
(C++的cwctype
)中聲明.
單字節 | 寬字節 | 描述 |
---|---|---|
isalnum
|
iswalnum
|
是否為字母數字 |
isalpha
|
iswalpha
|
是否為字母 |
islower
|
iswlower
|
是否為小寫字母 |
isupper
|
iswupper
|
是否為大寫字母 |
isdigit
|
iswdigit
|
是否為數字 |
isxdigit
|
iswxdigit
|
是否為16進制數字 |
iscntrl
|
iswcntrl
|
是否為控制字符 |
isgraph
|
iswgraph
|
是否為圖形字符(例如,空格、控制字符都不是) |
isspace
|
iswspace
|
是否為空格字符(包括制表符、回車符、換行符等) |
isblank
|
iswblank
|
是否為空白字符 (C99/C++11新增)(包括水平制表符) |
isprint
|
iswprint
|
是否為可打印字符 |
ispunct
|
iswpunct
|
是否為標點 |
tolower
|
towlower
|
轉換為小寫 |
toupper
|
towupper
|
轉換為大寫 |
不適用 | iswctype
|
檢查一個wchar_t 是否是屬於指定的分類
|
不適用 | towctrans
|
使用指定的變換映射來轉換一個wchar_t (實際上是大小寫的轉換)
|
不適用 | wctype
|
返回一個寬字符的類別,用於iswctype 函數
|
不適用 | wctrans
|
返回一個變換映射,用於 towctrans
|
參考文獻
[編輯]- ^ ISO/IEC 9899:1999 specification (PDF). . p. 193, § 7.4 [2013-06-20]. (原始內容 (PDF)存檔於2011-01-24).
外部連結
[編輯]
維基教科書中的相關電子教學:C Character Class Test Library

維基教科書中的相關電子教學:C character classification