C ctype.h Library
C ctype.h Library
The ctype.h library in C provides functions to test and manipulate characters. Itβs very useful for validating input, parsing text, and formatting strings.
All functions in ctype.h work with int values representing characters (usually char).
π Common Functions in ctype.h
1οΈβ£ Character Testing Functions
| Function | Description | Example |
|---|---|---|
isalnum(int c) |
Checks if character is alphanumeric (a-z, A-Z, 0-9) | isalnum('A') β true |
isalpha(int c) |
Checks if character is alphabetic | isalpha('1') β false |
isdigit(int c) |
Checks if character is a digit | isdigit('5') β true |
islower(int c) |
Checks if character is lowercase | islower('a') β true |
isupper(int c) |
Checks if character is uppercase | isupper('B') β true |
isspace(int c) |
Checks for whitespace (' ', '\t', '\n') |
isspace(' ') β true |
ispunct(int c) |
Checks if character is punctuation | ispunct('!') β true |
isxdigit(int c) |
Checks if character is hexadecimal digit | isxdigit('F') β true |
isprint(int c) |
Checks if character is printable | isprint('\n') β false |
isgraph(int c) |
Checks if character has graphic representation | isgraph(' ') β false |
2οΈβ£ Character Conversion Functions
| Function | Description | Example |
|---|---|---|
tolower(int c) |
Converts uppercase to lowercase | tolower('A') β 'a' |
toupper(int c) |
Converts lowercase to uppercase | toupper('b') β 'B' |
3οΈβ£ Example: Character Validation and Conversion
Sample Output:
4οΈβ£ Example: Count Character Types in a String
Output:
π Summary Table
| Function | Purpose |
|---|---|
isalnum |
Checks alphanumeric |
isalpha |
Checks alphabetic |
isdigit |
Checks digits |
islower |
Checks lowercase letters |
isupper |
Checks uppercase letters |
isspace |
Checks whitespace characters |
ispunct |
Checks punctuation |
isxdigit |
Checks hexadecimal digit |
isprint |
Checks printable characters |
isgraph |
Checks graphic characters |
tolower |
Converts to lowercase |
toupper |
Converts to uppercase |
β Notes
-
Functions expect int values, usually casted from
char. -
Always include
#include <ctype.h>. -
Useful for input validation, parsing, and formatting strings.
-
Can be combined with
string.hfor advanced string processing.
