Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to split a string with multiple separators in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_TOKENS 64
#define TOKEN_LEN 32

void splitByDelimiters(const char* input, const char* delimiters, char tokens[][TOKEN_LEN], int* count) {
    char temp[strlen(input) + 1];
    strcpy(temp, input);

    char* token = strtok(temp, delimiters);
    *count = 0;

    while (token != NULL && *count < MAX_TOKENS) {
        int tlen = strlen(token);
        strncpy(tokens[*count], token, tlen);
        tokens[*count][tlen] = '\0'; // Ensure null-termination
        (*count)++;
        token = strtok(NULL, delimiters);
    }
}

int main() {
    const char* input = "abc,defg;hijk|lmnop-qrst_uvwxyz";
    const char* delimiters = ",;|-_";
    char tokens[MAX_TOKENS][TOKEN_LEN];
    int tokenCount = 0;

    splitByDelimiters(input, delimiters, tokens, &tokenCount);

    for (int i = 0; i < tokenCount; ++i) {
        printf("%s\n", tokens[i]);
    }

    return 0;
}



/*
run:

abc
defg
hijk
lmnop
qrst
uvwxyz

*/



answered Jul 21, 2025 by avibootz
...