要了解其strtok()
工作原理,首先需要知道什么是静态变量。该链接很好地解释了...。
操作的关键strtok()
是保留两次相继调用之间的最后一个分隔符的位置(这就是为什么strtok()
继续解析null pointer
在连续调用中被调用时传递给它的非常原始的字符串的原因)。
看一下我自己的strtok()
实现,zStrtok()
该实现与所提供的功能截然不同。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;
}
这是一个示例用法
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)
该代码来自我在Github上维护的一个名为zString 的字符串处理库。看一下代码,甚至贡献一下:)
https://github.com/fnoyanisi/zString
strtok()
通过在返回之前使用NUL终止标记来修改其参数字符串。如果您尝试检查整个缓冲区(str []),则会看到在连续调用之间对其进行了修改strtok()
。