<ctype.h> LibraryThe <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.
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:
isalpha(c): Checks if the character is a letter (A-Z or a-z).isdigit(c): Checks if the character is a decimal digit (0-9).isalnum(c): Checks if the character is alphanumeric (a letter OR a digit).isspace(c): Checks if the character is a whitespace character (space, newline \n, tab \t, etc.).islower(c): Checks if the letter is lowercase.isupper(c): Checks if the letter is uppercase.#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; }
The <ctype.h> library also provides tools to manipulate the case of characters.
toupper(c): Converts a lowercase letter to uppercase. If the character is already uppercase, or if it is a number/symbol, it returns the character unchanged.tolower(c): Converts an uppercase letter to lowercase.#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; }
Which function checks if a character is either a letter OR a number?