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

Strip leading and trailing whitespace from a string in place, keeping any whitespace in the middle.

Task

Implement void trim(char *s) that removes whitespace (any character for which isspace is true) from the start and end of s, shifting the remaining text to the front and NUL-terminating it. Internal whitespace is preserved. The string is modified in place — no allocations.

Input

A NUL-terminated, writable string s.

Output

No return value. s is rewritten in place with surrounding whitespace removed.

Example

"  hello  "    ->   "hello"
"\thi\n"      ->   "hi"
"   "          ->   ""          (all whitespace)
"no_change"    ->   "no_change"
"a b c"        ->   "a b c"     (internal whitespace kept)

Edge cases

  • All-whitespace input becomes the empty string.
  • A string with no surrounding whitespace is unchanged.
  • Empty string and single-character inputs are handled.

Rules

  • No allocations or helper buffers. Use memmove (not memcpy) to shift bytes down — the source and destination overlap.

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

A NUL-terminated writable string s.

Output format

No return value; s is trimmed in place.

Constraints

No allocations or helper buffers. Use memmove (regions overlap), and re-NUL-terminate.

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.