Library contents

C strtok

Tokenize a writable byte string at any character in a delimiter set.

A simple example

strtok

  1. Start with a,b
  2. Do this Split at the comma
  3. Result a and b
The comma separates two nonempty fields.

Syntax

C 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
./lesson

Read 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.

From the programchar stops[] = "Lab,Gate"
First output lineLab
lesson.c
#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;
}
Output
Lab
Gate

strtok edits a writable array and returns each nonempty token.

Advertisements

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.

From the programchar row[] = "tea,,rice"
Result2
lesson.c
#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;
}
Output
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.

Givenmic,stand,cable
Worked result3

What to watch for

strtok modifies the array, skips empty fields and keeps internal iteration state. It is unsuitable for nested tokenization.

Documentation for strtok