Course contentsShow
← C
Lesson 429 of 1,2196. Arrays and StringsFree lesson

Tokenizing strings with `strtok`

Tokenizing strings with strtok

What you'll learn: How to chop a single string into smaller pieces based on specific characters like spaces or commas.

Imagine you have a long string of beads, but every few beads, there is a large red knot. If you wanted to study each section of beads individually, you would need to cut the string at every knot. In C, strtok is the pair of scissors that cuts your string into these smaller pieces, called "tokens."

How it works

The strtok function (from <string.h>) searches a string for "delimiters"—characters you choose to act as boundaries. When it finds one, it effectively "chops" the string there and gives you back a pointer to the start of that piece.

However, strtok is a bit quirky. To get the first piece, you give it the string name. To get every piece after that, you pass NULL instead. This tells the function, "Keep working on the same string you started with."

A practical example

Let’s say we have a sentence and we want to extract every individual word, using a space as our delimiter.

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Learning C is fun";
    char *token;

    // Get the first token
    token = strtok(str, " ");

    // Walk through the rest of the string
    while (token != NULL) {
        printf("Token: %s\n", token);
        
        // Pass NULL to get the next token from the same string
        token = strtok(NULL, " ");
    }

    return 0;
}

Important things to remember

  1. It changes the original: strtok is destructive. It replaces the delimiters (like the spaces in our example) with \0 (null terminators) to create the smaller strings. If you need the original sentence intact later, make a copy first.
  2. Multiple delimiters: You can provide multiple characters at once, like ", .!". The function will treat any of those characters as a reason to "cut" the string.
  3. The NULL signal: When there are no more tokens left to find, strtok returns NULL. This is why we use a while loop to keep grabbing pieces until the function tells us it’s finished.

Key takeaway

Use strtok to split strings into parts, passing the string once and then NULL for subsequent pieces.