Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strtok — splitting a string into tokens

strtok splits a writable string into nonempty tokens, overwriting delimiters and remembering where to continue.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
char *strtok(char * restrict s1, const char * restrict s2);

strtok from <string.h> treats s2 as a set of delimiter characters, not a substring. It skips leading and repeated delimiters: empty tokens are not produced.

Pass a writable, null-terminated string first; pass NULL as s1 subsequently. s2 may change between calls. The result points into the original array, or is NULL when no tokens remain.

The delimiter ending a token becomes '\0'. Never pass a string literal; copy input you need preserved.

Saved state prevents interleaving independent tokenizations. Continuing a sequence in another thread has undefined behavior. The example skips repeated delimiters.

Examples

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

int main(void)
{
    char text[] = ",red;;green,blue,";
    char *token = strtok(text, ",;");

    while (token != NULL) {
        puts(token);
        token = strtok(NULL, ",;");
    }

    return 0;
}

Result

red
green
blue

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources