C <ctype.h>

C Character Functions: The <ctype.h> Library

The <ctype.h> header file in C provides a set of highly optimized functions specifically for analyzing and modifying single characters. These functions are incredibly useful for parsing text, validating user input (like checking if a string only contains letters), and formatting data.


1. Character Classification Functions

Classification functions allow you to check what "type" a specific character is. They take an integer (the character's ASCII value) as input and return a non-zero integer (true) if the character belongs to the category, and 0 (false) if it does not.

Here are the most commonly used classification functions:

Classification Example

#include <stdio.h>
#include <ctype.h>

int main() { char test_char = '7'; if (isdigit(test_char)) { printf("'%c' is a number.\n", test_char); } else if (isalpha(test_char)) { printf("'%c' is a letter.\n", test_char); } else { printf("'%c' is a symbol or whitespace.\n", test_char); } return 0; }


2. Character Conversion Functions

The <ctype.h> library also provides tools to manipulate the case of characters.

Converting a String to Uppercase

#include <stdio.h>
#include <ctype.h>

int main() { char text[] = "Hello World 123!"; printf("Original: %s\n", text); printf("Modified: "); // Loop through the string until the null terminator is hit for (int i = 0; text[i] != '\0'; i++) { putchar(toupper(text[i])); // Convert and print each character } printf("\n"); return 0; }


Exercise

?

Which function checks if a character is either a letter OR a number?