C alternative to PHP's explode function

344

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\n", res[i]);
    free(res[i]);
}
free(res);
531

Answer

Solution:

Usestrtok(). From the man page for it:

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.

In other words, loop through your string and keep callingstrtok() until it returnsNULL in order to get all the words (that would be split on the delimiters specified to the first call ofstrtok()) returned aschar*.

People are also looking for solutions to the problem: php - second image in array can be saved on localhost but first one always get 404 not found

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.