Per capire come strtok()funziona, è necessario prima sapere cos'è una variabile statica . Questo link lo spiega abbastanza bene ....
La chiave per il funzionamento di strtok()è preservare la posizione dell'ultimo separatore tra chiamate seccessive (ecco perché strtok()continua ad analizzare la stringa molto originale che gli viene passata quando viene invocato con a null pointernelle chiamate successive) ..
Dai un'occhiata alla mia strtok()implementazione, chiamata zStrtok(), che ha una funzionalità leggermente diversa da quella fornita dastrtok()
char *zStrtok(char *str, const char *delim) {
static char *static_str=0; /* var to store last address */
int index=0, strlength=0; /* integers for indexes */
int found = 0; /* check if delim is found */
/* delimiter cannot be NULL
* if no more char left, return NULL as well
*/
if (delim==0 || (str == 0 && static_str == 0))
return 0;
if (str == 0)
str = static_str;
/* get length of string */
while(str[strlength])
strlength++;
/* find the first occurance of delim */
for (index=0;index<strlength;index++)
if (str[index]==delim[0]) {
found=1;
break;
}
/* if delim is not contained in str, return str */
if (!found) {
static_str = 0;
return str;
}
/* check for consecutive delimiters
*if first char is delim, return delim
*/
if (str[0]==delim[0]) {
static_str = (str + 1);
return (char *)delim;
}
/* terminate the string
* this assignmetn requires char[], so str has to
* be char[] rather than *char
*/
str[index] = '\0';
/* save the rest of the string */
if ((str + index + 1)!=0)
static_str = (str + index + 1);
else
static_str = 0;
return str;
}
Ed ecco un esempio di utilizzo
Example Usage
char str[] = "A,B,,,C";
printf("1 %s\n",zStrtok(s,","));
printf("2 %s\n",zStrtok(NULL,","));
printf("3 %s\n",zStrtok(NULL,","));
printf("4 %s\n",zStrtok(NULL,","));
printf("5 %s\n",zStrtok(NULL,","));
printf("6 %s\n",zStrtok(NULL,","));
Example Output
1 A
2 B
3 ,
4 ,
5 C
6 (null)
Il codice proviene da una libreria di elaborazione delle stringhe che mantengo su Github , chiamata zString. Dai un'occhiata al codice o contribuisci anche tu :)
https://github.com/fnoyanisi/zString
strtok()modifica la sua stringa di argomenti terminando i token con NUL prima di tornare. Se provi ad esaminare l'intero buffer (str []) vedrai che viene modificato tra le successive chiamate astrtok().