typestar

Classifying characters in C

ctype.h answers what a character is, without hard-coding ASCII ranges.

int count_digits(const char *text) {
    int digits = 0;
    for (const char *p = text; *p != '\0'; p++) {
        unsigned char c = (unsigned char) *p;
        if (isdigit(c)) {
            digits++;
        }
    }
    return digits;
}

void shout(char *text) {
    for (char *p = text; *p; p++) {
        *p = (char) toupper((unsigned char) *p);
    }
}

How it works

  1. isalpha, isdigit and isspace classify one character.
  2. toupper and tolower convert it.
  3. Pass the character as an unsigned char to stay defined.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
288
Tokens
107
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 5 of 5 in Arrays & strings, step 26 of 35 in Language basics.

← Previous Next →