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

标签 c++ c string pointers strtok

这是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 分钟,但在互联网上没有找到解释。

最佳答案

strtok() 通过使用静态变量将一些数据保存在自身内部。这样,strtok() 可以从上次调用时中断的点继续搜索。为了向 strtok() 发出您想要继续搜索相同字符串的信号,您需要传递一个 NULL 指针作为它的第一个参数。 strtok() 检查第一个参数是否为 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 = '\0';
        lastToken = tmp + 1;
    } else {
        /* Last segment, remember that. */
        lastToken = NULL;
    }

    return s1;
}

关于c++ - strtok() - 为什么必须传递 NULL 指针才能获取字符串中的下一个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29638598/

相关文章:

java - 字符串数组反转Java

字符串距离,仅换位

c++ - C++03 中的模板函数返回类型推导

c++ - 用于 mingw 的 msi.h

c - 将结构体实例分配给 C 中的内部嵌套结构体

c - `extern` 什么时候对于 C 中的变量是不可避免的?

sql - 批量更新 Excel 文件连接字符串

c++ - 当 Lua 绑定(bind)在该类中时,使用 LuaBind 在该类中调用 Lua 函数

c++ - 哪个 HRESULT 文字常量会使 SUCCEEDED() 宏失败?

c - 带有位域的奇怪大小的结构