这是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/