#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
*/