C strtok
Tokenize a writable byte string at any character in a delimiter set.
A simple example
strtok
- Start with a,b
- Do this Split at the comma
- Result a and b
Syntax
strtok(stops, ",")
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonRead a simple route manifest
A transit or dispatch system receives journey information as a sequence of stops or handoffs. Preserve their order when interpreting or displaying the route so the next destination is clear.
#include <stdio.h>
#include <string.h>
int main(void) {
char stops[] = "Lab,Gate";
for (char *stop = strtok(stops, ","); stop; stop = strtok(NULL, ",")) puts(stop);
return 0;
}
Lab Gate
strtok edits a writable array and returns each nonempty token.
Handle consecutive separators
A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.
#include <stdio.h>
#include <string.h>
int main(void) {
char row[] = "tea,,rice";
int count = 0;
for (char *item = strtok(row, ","); item; item = strtok(NULL, ",")) ++count;
printf("%d\n", count);
return 0;
}
2
Empty fields disappear. Choose a different parser for a spreadsheet where blank cells matter.
Count a choir equipment list
A teacher receives one comma-separated line of items. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.
What to watch for
strtok modifies the array, skips empty fields and keeps internal iteration state. It is unsuitable for nested tokenization.