CodeBlanks Logo Icon CodeBlanks

strtok

Learn to split a string into tokens with strtok.

strtok: splitting a string into tokens

The strtok function splits a string into pieces by specified delimiter characters. It comes with the <string.h> header. In the first call you pass the string; in later calls you pass NULL.

char text[] = "elma,armut,muz";
char *tok = strtok(text, ",");
// tok = "elma"

Each call returns the next piece. When a delimiter is found, it is treated as the end of the current piece. When all pieces are done, it returns NULL. To split the same string again, you must start over.

The strtok loop

To get all pieces, you call strtok inside a while loop. In the first call you pass the string; in later calls you pass NULL.

char text[] = "elma,armut,muz";
char *tok = strtok(text, ",");
while (tok != NULL) {
    printf("%s\n", tok);
    tok = strtok(NULL, ",");
}

The loop prints one piece per step; it ends when strtok returns NULL. Passing NULL in later calls makes the function remember the previous string. This is the standard pattern to process words one by one.

Practice Print comma-separated fruits

Use strtok to split "elma,armut,muz" by commas and print each piece on its own line with printf. Use a while loop that continues until strtok returns NULL. Include the <string.h> header.

Starter code

main.c
#include <stdio.h>

int main(void) {
    char text[] = "elma,armut,muz";
    /* Split into pieces with strtok; print each piece with printf */
    return 0;
}

Sample solution

main.c
#include <string.h>
char *tok = strtok(text, ",");
while (tok != NULL) {
    printf("%s\n", tok);
    tok = strtok(NULL, ",");
}

Expected output

elma
armut
muz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: strtok first call

Question
char *tok = ____(text, ",");
Answer
char *tok = strtok(text, ",");

Explanation: In the first strtok call you pass the string.

2 What should the first argument be to get the second piece with strtok?

  • The same string
  • An empty string
  • NULL Correct answer
  • The delimiter

Explanation: In later calls you pass NULL; strtok remembers the previous string.

3 Match concept to explanation

Term Meaning
strtok Splits a string
NULL Next call
delimiter Delimiter character
token Piece

All lessons in Beginner