So, i'm looking for a C function that does the equivalent to PHP's explode function. For those who are not familiar: Explode grabs a string and parses each entry separated by the given char/escape sequence. the best part about this function is its return value, which is an already forged array with all the entries. problem is, this doesn't seem to exist in C. the closest function available is strchr but it returns only a pointer to the first ocurrence of the split.
edit: here's the function, although it has a different behaviour (like the return value differs) it's what i want.
int explode(char* str, char* delim, char ***r) {
char **res = (char**) malloc(sizeof(char*) * strlen(str));
char *p;
int i = 0;
while (p = strtok(str, delim)) {
res[i] = malloc(strlen(p) + 1);
strcpy(res[i], p);
++i;
str = NULL;
}
res = realloc(res, sizeof(char*) * i);
*r = res;
return i;
}
it's possible to call it this way:
char str[] = "test1|test2|test3";
char** res;
int count = explode(str, "|", &res);
int i;
for (i = 0; i < count; ++i) {
printf("%s
", res[i]);
free(res[i]);
}
free(res);