typestar

Trimming whitespace in C

Trimming in place: walk forward for the start, backward for the end.

char *trim(char *text) {
    while (isspace((unsigned char) *text)) {
        text++;
    }
    char *end = text + strlen(text);
    while (end > text && isspace((unsigned char) end[-1])) {
        end--;
    }
    *end = '\0';
    return text;
}

int is_blank(const char *text) {
    for (; *text; text++) {
        if (!isspace((unsigned char) *text)) {
            return 0;
        }
    }
    return 1;
}

How it works

  1. Leading space is skipped by advancing a pointer.
  2. Trailing space is removed by writing an earlier NUL.
  3. Returning the new start avoids copying anything.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
325
Tokens
117
Three-star pace
100 tpm

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

Type this snippet

Step 3 of 3 in Splitting & parsing, step 10 of 13 in Strings & text.

← Previous Next →