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
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.