2016-03-17 47 views
-4

这是的strtok函数的例子...我需要一个解释用于该块:的strtok函数c解释

while (pch != NULL) 
{ 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " "); 
} 
return 0; 

尤其pch = strtok (NULL, " ");

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="This a sample string"; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," "); 
    while (pch != NULL) 
    { 
     printf ("%s\n",pch); 
     pch = strtok (NULL, " "); 
    } 
    return 0; 
} 
+6

你看过[函数文档](http://en.cppreference.com/w/c/string/byte/strtok)吗? –

+1

这是[strtok的在线手册页](http://linux.die.net/man/3/strtok)。阅读完后你有什么特别的问题吗? –

+0

我知道这个函数从字符串中获取标记,但是在这一行[strtok(NULL,“”); ]我不知道我将得到它的令牌的字符串在哪里! –

回答

1

的strtok()是从一个函数标准C库。标准C库有一些开源实现。例如:下面的链接是来自Microsoft的一个版本。

http://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crt/strtok.c.htm

你可以在代码中清楚地看到:

/* Skip leading delimiters if new string. */ 
if (s1 == NULL) { 
    s1 = lastToken; 
    if (s1 == NULL)   /* End of story? */ 
    return NULL; 
} else 
..... 

变量 “lastToken” 被用于跟踪strtok的状态()。

这就是第二个标记应该将NULL传递给strtok()的原因。