String Token strtok函数逻辑

Ado*_*aim 1 c string strtok

我正在学习C标准函数的字符串操作.当我学习这些东西时,我面临着strtok函数和以下代码.

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

int main()
{
   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL )
   {
      printf( " %s\n", token );
      token = strtok(NULL, s);
   }

   return(0);
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么在while循环中,strtok与null一起使用?为什么在这里使用null?因为在strtok函数定义中有类似的东西(这个函数使用第二个参数将第一个参数字符串分解为一系列标记.)

Iha*_*imi 7

因为它使用了一个static指向你正在使用的字符串的内部指针,所以如果你想让它在同一个字符串上运行,你只需要将它NULL作为第一个参数调用它,并让它使用它的内部指针.如果使用非null第一个参数调用它,那么它将使用新指针覆盖指针.

反过来,这意味着这strtok()不是可重入的.所以你通常只是在简单的情况下使用它,重入是重要的更复杂的情况(如多线程程序,或处理多个字符串)需要不同的方法.

一种方法是在POSIX系统上,您可以使用strtok_r()其中一个额外的参数作为" 内部 "指针使用.

查看本手册以了解更多信息.