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);
有帮助吗?

解决方案

Use strtok(). 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 calling strtok() until it returns NULL in order to get all the words (that would be split on the delimiters specified to the first call of strtok()) returned as char*.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top