strtok() in C: Split a String into Tokens

strtok() splits a modifiable C string into tokens using one or more delimiter characters. The first call receives the string; later calls pass NULL to continue from the previous position.

Syntax Top ↑

char *token = strtok(string, delimiters);
token = strtok(NULL, delimiters);

Split a Hyphen-Separated String Top ↑

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

int main(void) {
    char text[] = "Welcome-to-plus2net";
    char *token = strtok(text, "-");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, "-");
    }

    return 0;
}

Output

Welcome
to
plus2net

Use Multiple Delimiter Characters Top ↑

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

int main(void) {
    char text[] = "apple, banana, orange. grape";
    char *token = strtok(text, ",. ");

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, ",. ");
    }

    return 0;
}

Output

apple
banana
orange
grape

Read the String and Delimiter Top ↑

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

int main(void) {
    char text[100];
    char delimiters[20];

    printf("Enter a string: ");
    if (fgets(text, sizeof(text), stdin) == NULL) {
        return 1;
    }

    printf("Enter delimiter characters: ");
    if (fgets(delimiters, sizeof(delimiters), stdin) == NULL) {
        return 1;
    }
    delimiters[strcspn(delimiters, "\n")] = '\0';

    char *token = strtok(text, delimiters);
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, delimiters);
    }

    return 0;
}

strtok() Changes the Original String Top ↑

strtok() writes null characters into the input array to terminate each token. Use a writable character array, not a string literal, and make a copy first if the original text must be preserved.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer