C: correct usage of strtok_r

前端 未结 4 1468
温柔的废话
温柔的废话 2020-11-30 07:11

How can I use strtok_r instead of strtok to do this?

char *pchE = strtok(NULL, \" \");

Now I\'m trying to use strtok_r properl

4条回答
  •  攒了一身酷
    2020-11-30 07:48

    Tested example:

    #include 
    #include 
    
    int main(void)
    {
        char str[] = "1,22,333,4444,55555";
        char *rest = NULL;
        char *token;
    
        for (token = strtok_r(str, ",", &rest);
             token != NULL;
             token = strtok_r(NULL, ",", &rest)) {   
            printf("token:%s\n", token);
        }
    
        return 0;
    }
    

    Result.

    token:1
    token:22
    token:333
    token:4444
    token:55555
    

    Test: http://codepad.org/6xRdIecI

    From linux documentation where emphasis is mine:

    char *strtok_r(char *str, const char *delim, char **saveptr);
    

    The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

    On the first call to strtok_r(), str should point to the string to be parsed, and the value of saveptr is ignored. In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call.

    Different strings may be parsed concurrently using sequences of calls to strtok_r() that specify different saveptr arguments.

提交回复
热议问题