basics · beginner · ~15 min

Trim leading and trailing whitespace in place

Use `memmove` to shift bytes left and a scan to truncate the right.

Challenge

Implement void trim(char *s) that mutates s in place to remove leading and trailing whitespace (as defined by isspace).

  • Internal whitespace is preserved.
  • The result is NUL-terminated.

Examples

"  hello  "       -> "hello"
"\thi\n"        -> "hi"
"   "             -> ""
""                -> ""
"no_change"       -> "no_change"
"a b c"           -> "a b c"   // internal preserved
" abc "           -> "abc"

Edge cases

  • All-whitespace input → empty string.
  • No whitespace at either end → unchanged.
  • A single character.

Why this matters

Every CSV reader, every config-file parser, every header reader in C trims whitespace. Doing it without allocating is the standard idiom — and a great exercise in memmove and pointer scanning.

Input format

Null-terminated mutable string.

Output format

s is mutated in place.

Constraints

No allocations; no helper buffers. Use memmove, not memcpy, because source and destination overlap.

Starter code

void trim(char *s) { /* TODO */ }

Common mistakes

Using memcpy on overlapping regions — undefined behaviour. Forgetting to NUL-terminate after truncating the right side.

Edge cases to handle

All whitespace; empty string; only-leading or only-trailing whitespace.

Complexity

O(strlen(s)).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.