strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记?

strtok() - Why you have to pass the NULL pointer in order to get the next token in the string?

这是strtok()的解释

#include <string.h>
char* strtok( char* s1, 
              const char* s2 );*

The first call to strtok() returns a pointer to the first token in the string pointed to by s1. Subsequent calls to strtok() must pass a NULL pointer as the first argument, in order to get the next token in the string.

但我不知道,为什么必须传递 NULL 指针才能获取字符串中的下一个标记。我搜索了大约15分钟,但在互联网上没有找到解释。

如果您传递一个非 NULL 值,则表示您要求它开始标记不同的字符串。

如果您传递 NULL 值,则表示您要求继续对与之前相同的内容进行分词。

strtok() 通过使用静态变量在自身内部保留一些数据。这样,strtok() 可以从上次调用中断的地方继续搜索。要向 strtok() 表明您要继续搜索同一个字符串,请将 NULL 指针作为其第一个参数传递。 strtok() 检查第一个参数是否为 NULL,如果是,则使用其当前存储的数据。如果第一个参数不为空,则将其视为新搜索并重置所有内部数据。

也许您能做的最好的事情就是搜索 strtok() 函数的实际实现。我在这里找到了一个小到 post 的,所以你可以了解如何处理这个 NULL 参数:

/* Copyright (c) Microsoft Corporation. All rights reserved. */

#include <string.h>

/* ISO/IEC 9899 7.11.5.8 strtok. DEPRECATED.
 * Split string into tokens, and return one at a time while retaining state
 * internally.
 *
 * WARNING: Only one set of state is held and this means that the
 * WARNING: function is not thread-safe nor safe for multiple uses within
 * WARNING: one thread.
 *
 * NOTE: No library may call this function.
 */

char * __cdecl strtok(char *s1, const char *delimit)
{
    static char *lastToken = NULL; /* UNSAFE SHARED STATE! */
    char *tmp;

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

    /* Find end of segment */
    tmp = strpbrk(s1, delimit);
    if (tmp) {
        /* Found another delimiter, split string and save state. */
        *tmp = '[=10=]';
        lastToken = tmp + 1;
    } else {
        /* Last segment, remember that. */
        lastToken = NULL;
    }

    return s1;
}