Learn C
#include "arraysstrings/strtok.h"

Tokenizing with strtok & strtok_r in C

#concept

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.

#how it works
1

Destructive splitting

strtok(buf, " ,") replaces each delimiter with a terminator and returns token pointers into buf — the original string is consumed.

2

NULL continues

First call passes the buffer, subsequent calls pass NULL to resume — the hidden static state that breaks reentrancy.

3

strtok_r externalizes state

strtok_r(buf, ",", &save) keeps progress in your save pointer — nestable loops and threads each carry their own.

4

Empty fields vanish

Delimiter runs collapse, so a,,b tokenizes as two fields — formats needing empties need manual scanning.

#example
#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;
}
Output
one
two
three
count=3
1The writable array (not a literal — strtok modifies!) plus explicit save pointer set up reentrant tokenizing.
2Each call returns the next comma-delimited token until NULL ends the loop — three tokens total.
3All three print plus the count — the buffer now holds terminators where commas were.
#use cases
Splitting owned, modifiable buffers on delimiter sets
Nested tokenizing loops that plain strtok would corrupt
Thread-safe parsing with per-thread save pointers
Recognizing when empty fields demand manual scanning instead

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.