Course contentsShow
← C
Lesson 853 of 1,21912. The Standard LibraryFree lesson

Tokenizing strings with `strtok`

Tokenizing strings with strtok

What you'll learn: How to chop a single string into smaller pieces based on a specific character like a comma or a space.

Imagine you have a long string like "bread,milk,eggs,butter". To a computer, this is just one long sequence of characters. But to you, it’s a list of four distinct items. In C, the process of breaking this sequence into individual pieces is called tokenizing, and the strtok function is your primary tool for the job.

How strtok works

Think of strtok like a pair of scissors. You tell the scissors which character marks the "cut" (the delimiter). When strtok finds that character, it replaces it with a null terminator (\0), effectively ending the string right there and returning a pointer to the start of that "token."

Here is the catch: strtok is stateful. The first time you call it, you give it the string you want to chop. For every call after that, you pass NULL to tell the function, "Keep working on the same string where you left off."

Seeing it in action

To use strtok, you need the <string.h> header. Note that strtok modifies the original string, so never use it on a string literal (like "hello"); always use a character array.

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

int main() {
    char list[] = "Apple,Banana,Cherry";
    char *token;

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

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

    return 0;
}

The "NULL" trick

In the code above, the first call to strtok initializes the process. It finds "Apple," replaces the first comma with a \0, and returns a pointer to "Apple."

When we call strtok(NULL, ",") inside the loop, the function remembers its position inside the list array. It skips past the null terminator it just created, finds "Banana," and repeats the process. Once there are no more delimiters left, it returns NULL, which tells our loop to stop.

Key takeaway

Use strtok with the string name first, then with NULL in a loop to break a string into smaller pieces at specific delimiters.