0Pricing
C Academy · Lesson

strtok and Tokenizing

Split strings.

What is tokenizing?

Tokenizing means splitting a string into smaller pieces (tokens) separated by delimiter characters.

For example, splitting "a,b,c" on commas gives the tokens a, b, and c. C provides strtok for this.

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

int main(void) {
    char text[] = "a,b,c";
    char *token = strtok(text, ",");
    printf("First token: %s\n", token);
    return 0;
}

The strtok signature

char *strtok(char *str, const char *delim);

On the first call you pass the string. On subsequent calls you pass NULL so it continues where it left off. It returns the next token, or NULL when done.

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

int main(void) {
    char text[] = "red green blue";
    char *tok = strtok(text, " ");
    while (tok != NULL) {
        printf("%s\n", tok);
        tok = strtok(NULL, " ");
    }
    return 0;
}

All lessons in this course

  1. strlen, strcpy, strcat
  2. strcmp and Comparison
  3. strtok and Tokenizing
  4. memcpy and memset
← Back to C Academy