basics · beginner · ~15 min
Use `memmove` to shift bytes left and a scan to truncate the right.
Implement void trim(char *s) that mutates s in place to remove leading and trailing whitespace (as defined by isspace).
" hello " -> "hello"
"\thi\n" -> "hi"
" " -> ""
"" -> ""
"no_change" -> "no_change"
"a b c" -> "a b c" // internal preserved
" abc " -> "abc"
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.
Null-terminated mutable string.
s is mutated in place.
No allocations; no helper buffers. Use memmove, not memcpy, because source and destination overlap.
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.