Copy contents of strtok token in C

You must separate the line and then perform another split.

char *token = strtok(str, ",");
while(token){
    char *current_string = malloc(sizeof(char) * strlen(token));
    strcpy(current_string, token);

    char *tk = strtok(current_string, ":"); // KEY
    printf("key: %s ", tk);
    tk = strtok(0, ":");                    // VALUE
    printf("value: %s\r\n", tk);
    printf("%s\n", token);
    token = strtok(0, ",");
}

printf("Done\n");

Trying to copy the contents token, but at the same time there is a mess with what remains in the variable token. It processes only one line, not three. I suspect that the problem is related to strcpy(current_string, token), but I don’t know how I should do it.

+4
source share
1 answer

The function strtokuses an internal static buffer to track where it left off. This means that you cannot use it to re-parse two different lines.

In your specific case, with this call:

token = strtok(0, ",");

- current_string, token .

strtok_r. . , :

char *state1, *state2;
char *token = strtok_r(str, ",", &state1);
while(token){
    char *current_string = strdup(token);

    char *tk = strtok_r(current_string, ":", &state2); // KEY
    printf("key: %s ", tk);
    tk = strtok_r(NULL, ":", &state2);                    // VALUE
    printf("value: %s\r\n", tk);
    printf("%s\n", token);
    free(current_string);
    token = strtok_r(NULL, ",", &state1);
}

printf("Done\n");

, NULL strtok_r 0, NULL 0. , malloc/strcpy strdup, , free, .

strtok_r UNIX/Linux. Windows strtok_s, .

+5
source

Source: https://habr.com/ru/post/1694361/