Tokenizing with strtok & strtok_r in C
strtok splits a string on delimiter characters, returning one token per call — but it modifies the string in place (writing terminators over delimiters) and hides iteration state in a static buffer, making it non-reentrant and thread-unsafe. strtok_r takes an explicit save-pointer (char *saveptr) holding that state in the open, restoring reentrancy and thread safety.
Both skip leading delimiters and collapse runs, so empty fields vanish — CSV with ,, loses a column silently. For serious parsing, manual scanning or dedicated parsers beat both; for quick splitting of owned, modifiable buffers, strtok_r is the honest tool.
Destructive splitting
strtok(buf, " ,") replaces each delimiter with a terminator and returns token pointers into buf — the original string is consumed.
NULL continues
First call passes the buffer, subsequent calls pass NULL to resume — the hidden static state that breaks reentrancy.
strtok_r externalizes state
strtok_r(buf, ",", &save) keeps progress in your save pointer — nestable loops and threads each carry their own.
Empty fields vanish
Delimiter runs collapse, so a,,b tokenizes as two fields — formats needing empties need manual scanning.
#include <stdio.h>#include <string.h> int main(void) { char line[] = "one,two,three"; char *save = NULL; int n = 0; for (char *t = strtok_r(line, ",", &save); t; t = strtok_r(NULL, ",", &save)) { printf("%s\n", t); ++n; } printf("count=%d\n", n); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.