C: correct usage of strtok_r

前端 未结 4 1472
温柔的废话
温柔的废话 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:41

    I post a tested example to understand the correct usage of strtok_r() instead of using strtok() in nests.

    first lets take a string "y.o.u,a.r.e,h.e.r.e" and separate using the delimiters "," and "."

    using strtok()

    #include
    #include
    int main(void) {
    
            char str[]="y.o.u,a.r.e,h.e.r.e";
            const char *p=",", *q=".";
            char *a,*b;
    
            for( a=strtok(str,p) ; a!=NULL ; a=strtok(NULL,p) ) {
                    printf("%s\n",a);
                    for( b=strtok(a,q) ; b!=NULL ; b=strtok(NULL,q) )
                            printf("%s\n",b);
            }
    
            return 0;
    }
    

    OUTPUT:

    y.o.u
    y
    o
    u

    now lets use strtok_r() for same example

    using strtok_r()

    #include
    #include
    int main(void) {
    
            char str[]="y.o.u,a.r.e,h.e.r.e";
            const char *p=",",*q=".";
            char *a,*b,*c,*d;
    
            for( a=strtok_r(str,p,&c) ; a!=NULL ; a=strtok_r(NULL,p,&c) ) {
                    printf("%s\n",a);
    
                    for( b=strtok_r(a,q,&d) ; b!=NULL ; b=strtok_r(NULL,q,&d) )
                            printf("%s\n",b);
            }
    
            return 0;
    }
    

    OUTPUT:

    y.o.u
    y
    o
    u
    a.r.e
    a
    r
    e
    h.e.r.e
    h
    e
    r
    e

    therefore the strtok_r() has reentrant property whereas strtok() doesnot function like that.

提交回复
热议问题