Para entender cómo funciona strtok()
, primero hay que saber qué es static variable. This link lo explica bastante bien ...
La clave para el funcionamiento de strtok()
es preservar la ubicación del último separador entre llamadas seccessive (por eso strtok()
sigue analizar la cadena muy original que se pasa a ella cuando se invoca con un null pointer
en llamadas sucesivas). .
tenga una mirada en mi propia strtok()
aplicación, llamada zStrtok()
, que tiene una funcionalidad sligtly diferente a la proporcionada por strtok()
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;
}
Y aquí es un ejemplo de uso
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)
El código es de a string processing library I maintain on Github, llamado zString. Tener un vistazo al código, o incluso contribuir :) https://github.com/fnoyanisi/zString
'strtok()' modifica su cadena de argumento terminando tokens con NUL antes de volver. Si intentas examinar todo el búfer (str []) verás que se está modificando entre llamadas sucesivas a 'strtok()'. –
En lugar de ver 'str', mire' str [0] ',' str [1] ',' str [2] ', ... – pmg
@pmg: vi str [0] y str [1] .str [1] debería ser '\ 0', pero era un espacio allí. –