Site Tools


wiki:h-ctype

Table of Contents

<ctype.h>

<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.

Example

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;
}
wiki/h-ctype.md · Last modified: by 127.0.0.1