basics · beginner · ~15 min
Use `memmove` to shift bytes left and a scan to truncate the right.
Strip leading and trailing whitespace from a string in place, keeping any whitespace in the middle.
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.
A NUL-terminated, writable string s.
No return value. s is rewritten in place with surrounding whitespace removed.
" hello " -> "hello"
"\thi\n" -> "hi"
" " -> "" (all whitespace)
"no_change" -> "no_change"
"a b c" -> "a b c" (internal whitespace kept)
memmove (not memcpy) to shift bytes down — the source and destination overlap.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.
A NUL-terminated writable string s.
No return value; s is trimmed in place.
No allocations or helper buffers. Use memmove (regions overlap), and re-NUL-terminate.
void trim(char *s) { /* TODO */ }
Using memcpy on overlapping regions — undefined behaviour. Forgetting to NUL-terminate after truncating the right side.
All whitespace; empty string; only-leading or only-trailing whitespace.
O(strlen(s)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.