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,950 questions

51,892 answers

573 users

How to write an equivalent to PHP explode(string $separator, string $string, int $limit = INT_MAX): array in C

1 Answer

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

char **explode(const char *separator, const char *input, int limit, int *out_count) {
    char **result = NULL;
    int count = 0;
    size_t sep_len = strlen(separator);
    const char *start = input;
    const char *pos;

    while ((pos = strstr(start, separator)) != NULL && count < limit - 1) {
        size_t len = pos - start;
        char *token = (char *)malloc(len + 1);
        memcpy(token, start, len);
        token[len] = '\0';

        result = (char **)realloc(result, sizeof(char *) * (count + 1));
        result[count++] = token;

        start = pos + sep_len;
    }

    // Add the remaining part
    char *token = strdup(start);
    result = (char **)realloc(result, sizeof(char *) * (count + 1));
    result[count++] = token;

    *out_count = count;
    
    return result;
}

int main(void) {
    const char *text = "c++,c,python,php,java";
    const char *delimiter = ",";
    int limit = 3;
    int count = 0;

    char **parts = explode(delimiter, text, limit, &count);

    for (int i = 0; i < count; i++) {
        printf("%s\n", parts[i]);
        free(parts[i]);  // free each string
    }
    free(parts);  // free the array of pointers

    return 0;
}


 
 
/*
run:
   
6
   
*/

 



answered Nov 20, 2025 by avibootz

Related questions

...