<ctype.h> provides character classification (isalpha, isdigit, isspace) and conversion (toupper, tolower). These functions handle the full range of unsigned char correctly and respect locale.
Always cast to unsigned char when passing chars to avoid undefined behavior with negative signed values.
This example classifies characters in a string as letters, digits, or spaces.
// compile: gcc -o ctypeexample ctypeexample.c // run: ./ctypeexample // description: count character types in a string #include <ctype.h> #include <stdio.h> #include <string.h> int main() { const char* str = "Hello World 123"; int letters = 0, digits = 0, spaces = 0; for (size_t i = 0; str[i]; i++) { unsigned char c = (unsigned char)str[i]; if (isalpha(c)) letters++; else if (isdigit(c)) digits++; else if (isspace(c)) spaces++; } printf("letters=%d digits=%d spaces=%d\n", letters, digits, spaces); return 0; }
Character classification (return non-zero if true, zero if false):
isalpha(c): alphabetic letter (A-Z, a-z)isdigit(c): decimal digit (0-9)isalnum(c): alphanumeric (letter or digit)isspace(c): whitespace (space, tab, newline, etc.)isblank(c): space or tab (C99)isupper(c): uppercase letterislower(c): lowercase letterisxdigit(c): hexadecimal digit (0-9, a-f, A-F)ispunct(c): punctuationisprint(c): printable (not control character)isgraph(c): visible character (print except space)iscntrl(c): control character (ASCII 0-31, 127)isascii(c): ASCII character (0-127, non-standard)Case conversion:
toupper(c): convert to uppercase (returns character unchanged if not lowercase)tolower(c): convert to lowercase (returns character unchanged if not uppercase)Notes:
int (though typically passed char, which is promoted)isxxx((unsigned char)c) to avoid negative char UB