typestar

Case conversion and comparison in C

Converting in place, and comparing without regard to case.

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

int ci_compare(const char *a, const char *b) {
    while (*a && *b) {
        int x = tolower((unsigned char) *a);
        int y = tolower((unsigned char) *b);
        if (x != y) {
            return (x > y) - (x < y);
        }
        a++;
        b++;
    }
    return (*a != '\0') - (*b != '\0');
}

How it works

  1. toupper takes and returns an int, so cast on the way in and out.
  2. There is no portable case-insensitive strcmp in ISO C.
  3. Writing one is four lines, and it is exactly this.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
341
Tokens
140
Three-star pace
100 tpm

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

Type this snippet

Step 1 of 2 in Transforming, step 11 of 13 in Strings & text.

← Previous Next →