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

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

本文关键字:字符串 获取 下一个 指针 NULL 为什么 strtok      更新时间:2023-10-16

这是strtok()的解释。

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

对 strtok() 的第一次调用返回指向 S1 指向的字符串。对 strtok() 的后续调用必须传递 NULL 指针作为第一个参数,以便获取下一个令牌 字符串。

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

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

也许你能做的最好的事情就是搜索strtok()函数的实际实现。我找到了一个足够小的可以在这里发布它,所以你知道如何处理这个 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 = '';
        lastToken = tmp + 1;
    } else {
        /* Last segment, remember that. */
        lastToken = NULL;
    }
    return s1;
}

如果传递非 NULL 值,则会要求它开始标记不同的字符串。

如果传递 NULL 值,则会要求继续标记与以前相同的内容。