Many tasks start by splitting text into pieces: the words of a sentence, the fields of a CSV line, the parts of a key=value setting. C’s standard tool for this is strtok from <string.h>. It is handy but unusual: it changes the string it splits, it remembers its position between calls, and it silently skips empty fields. This lesson shows how to use strtok correctly and how to write a small splitter when its behaviour is not what you need.
In this lesson you will learn
- The two-step calling pattern of
strtok - Using several delimiter characters
- Why
strtokneeds a modifiable array - Parsing
key=valuepairs withstrchr - Keeping empty fields with a custom splitter
You should know strings and string functions.
Splitting with strtok
#include <stdio.h>
#include <string.h>
int main(void) {
/* strtok splits a string into tokens; it MODIFIES the string, so use an array */
char tags[] = "c, python,,java; sql";
const char *delims = ", ;"; /* any of these characters separates tokens */
int count = 0;
char *tok = strtok(tags, delims); /* first call: pass the string */
while (tok != NULL) {
printf("token %d: [%s]\n", ++count, tok);
tok = strtok(NULL, delims); /* later calls: pass NULL to continue */
}
/* The original array now has '\0' where the first delimiter of each gap was */
printf("tags after strtok: [%s]\n", tags);
/* Parsing "key=value" pairs */
char query[] = "name=Rina&city=Khulna&age=22";
for (char *pair = strtok(query, "&"); pair != NULL; pair = strtok(NULL, "&")) {
char *eq = strchr(pair, '=');
if (eq == NULL) continue;
*eq = '\0'; /* split the pair in two */
printf("%-5s -> %s\n", pair, eq + 1);
}
return 0;
}
Output
token 1: [c]
token 2: [python]
token 3: [java]
token 4: [sql]
tags after strtok: [c]
name -> Rina
city -> Khulna
age -> 22
- The first call passes the string; every later call passes
NULL, which tellsstrtokto continue where it stopped. It returnsNULLwhen no tokens remain. - The second argument is a set of delimiter characters, not a single separator string.
", ;"splits at any comma, space or semicolon, and runs of them count as one gap, so “python,,java” produced no empty token. strtokwrites'\0'into the string at each gap. That is whytagsprinted as just “c” afterwards, and why the string must be achararray. Passing a string literal is undefined behaviour and often crashes.- For
key=valuepairs, split on&first, then find=withstrchrand replace it with'\0'. The pair is now two strings: the key before and the value after.
Keeping Empty Fields
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A safe splitter that keeps empty fields and does not change its input */
static int split(const char *s, char sep, char out[][16], int max) {
int n = 0;
const char *start = s;
for (const char *p = s; ; p++) {
if (*p == sep || *p == '\0') {
if (n < max) {
size_t len = (size_t)(p - start);
if (len > 15) len = 15; /* truncate long fields */
memcpy(out[n], start, len);
out[n][len] = '\0';
n++;
}
if (*p == '\0') break;
start = p + 1;
}
}
return n;
}
int main(void) {
/* strtok skips empty fields, which is wrong for CSV data */
char row[] = "Arif,,EEE,3.41";
printf("strtok fields:");
for (char *t = strtok(row, ","); t; t = strtok(NULL, ","))
printf(" [%s]", t);
printf("\n");
char fields[8][16];
int n = split("Arif,,EEE,3.41", ',', fields, 8);
printf("split fields:");
for (int i = 0; i < n; i++) printf(" [%s]", fields[i]);
printf("\n");
/* Turning tokens into numbers */
char nums[] = "12 7 30 5";
int total = 0;
for (char *t = strtok(nums, " "); t; t = strtok(NULL, " "))
total += (int)strtol(t, NULL, 10);
printf("total = %d\n", total);
return 0;
}
Output
strtok fields: [Arif] [EEE] [3.41]
split fields: [Arif] [] [EEE] [3.41]
total = 54
- In the record “Arif,,EEE,3.41” the second field is empty, perhaps a missing phone number.
strtokskipped it, so every later field moved one position, a real bug in CSV processing. splitwalks the string once and cuts at every separator, so it returns four fields including the empty one. It copies the pieces into a separate array, so the input stays unchanged and can even be a string literal.- Each copy is limited to 15 characters plus
'\0', and themaxargument stops it writing past the output array. - Tokens are still text.
strtolturns each one into a number before adding them up.
String Splitting Tools
| Function | Use | Notes |
|---|---|---|
strtok(s, delims) | Split on any delimiter character | Modifies s; skips empty fields; not thread-safe |
strtok_r (POSIX) / strtok_s (C11 Annex K, MSVC) | Same, with your own position pointer | Safe for nested loops and threads |
strchr(s, c) | Find one character | Good for splitting once, such as at = |
strcspn(s, set) | Length of the prefix with none of set | Finds the next separator without modifying |
strspn(s, set) | Length of the prefix made only of set | Skips leading spaces or digits |
Common Mistakes
- Calling
strtokon a string literal such asstrtok("a,b", ","). - Passing the string again instead of
NULLon later calls, which returns the first token forever. - Nesting two
strtokloops, for example splitting lines and then words. The inner loop overwrites the outer loop’s saved position. Usestrtok_ror a custom splitter. - Expecting empty fields to appear as empty tokens.
Practice Exercises
Exercise 1. Count the words in " C is a small language ".
Show answer
char text[] = " C is a small language ";
int words = 0;
for (char *t = strtok(text, " "); t != NULL; t = strtok(NULL, " "))
words++;
printf("%d\n", words); /* 5 */
Here skipping empty tokens is exactly what you want, so strtok is a good fit.
Exercise 2. Split "2026-03-26" into year, month and day integers.
Show answer
char date[] = "2026-03-26";
int parts[3], i = 0;
for (char *t = strtok(date, "-"); t != NULL && i < 3; t = strtok(NULL, "-"))
parts[i++] = (int)strtol(t, NULL, 10);
printf("year %d, month %d, day %d\n", parts[0], parts[1], parts[2]);
sscanf(date, "%d-%d-%d", ...) is a shorter alternative for a fixed format like this.
Frequently Asked Questions
How do I keep the original string when using strtok?
Copy it first, for example with strcpy into another array, or with strdup (POSIX, and standard from C23), and split the copy. Remember to free a strdup copy.
Is strtok thread-safe?
No. It stores its position in a hidden static variable, so two threads, or two nested loops, interfere with each other. Use strtok_r on POSIX systems or strtok_s on Windows.
Summary
- Call
strtok(str, delims)once, thenstrtok(NULL, delims)until it returnsNULL. strtokmodifies its input, so pass achararray, never a literal.- It skips empty fields; write a custom splitter when they matter.
- Use
strtok_rfor nested loops or threads.
Next: math.h Functions in C.
