c++ - strtok() - Why you have to pass the NULL pointer in order to get the next token in the string? -
this explanation of strtok().
#include char strtok( char* s1, const char* s2 );*
the first call strtok() returns pointer first token in string pointed s1. subsequent calls strtok() must pass null pointer first argument, in order next token in string.
but don't know, why have pass null pointer in order next token in string. searched 15 minutes, didn't find explanation in internet.
strtok()
keeps data in static variables inside function can continue searching point left previous call. signal strtok()
want keep searching same string, pass null
pointer first argument. strtok()
checks whether null
, if so, uses stored data. if first parameter not null, treated new search , internal data resetted.
maybe best thing can search actual implementation of strtok()
function. i've found 1 small enough post here, idea of how handle null parameter:
/* copyright (c) microsoft corporation. rights reserved. */ #include <string.h> /* iso/iec 9899 7.11.5.8 strtok. deprecated. * split string tokens, , return 1 @ time while retaining state * internally. * * warning: 1 set of state held , means * warning: function not thread-safe nor safe multiple uses within * warning: 1 thread. * * note: no library may call function. */ char * __cdecl strtok(char *s1, const char *delimit) { static char *lasttoken = null; /* unsafe shared state! */ char *tmp; /* skip leading delimiters if new string. */ if ( s1 == null ) { s1 = lasttoken; if (s1 == null) /* end of story? */ return null; } else { s1 += strspn(s1, delimit); } /* find end of segment */ tmp = strpbrk(s1, delimit); if (tmp) { /* found delimiter, split string , save state. */ *tmp = '\0'; lasttoken = tmp + 1; } else { /* last segment, remember that. */ lasttoken = null; } return s1; }
Comments
Post a Comment