这是strtok()的解释。
#include <string.h>
char* strtok( char* s1,
const char* s2 );*
第一次调用 strtok() 返回指向 s1 指向的字符串中第一个标记的指针。为了获取字符串中的下一个标记,后续调用 strtok() 必须将第一个参数传递为 NULL 指针。但我不知道为什么必须传递 NULL 指针才能获取字符串中的下一个标记。我在互联网上搜索了大约 15 分钟,但没有找到解释。这是strtok()的解释。
#include <string.h>
char* strtok( char* s1,
const char* s2 );*
第一次调用 strtok() 返回指向 s1 指向的字符串中第一个标记的指针。为了获取字符串中的下一个标记,后续调用 strtok() 必须将第一个参数传递为 NULL 指针。但我不知道为什么必须传递 NULL 指针才能获取字符串中的下一个标记。我在互联网上搜索了大约 15 分钟,但没有找到解释。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 = '\0';
lastToken = tmp + 1;
} else {
/* Last segment, remember that. */
lastToken = NULL;
}
return s1;
}
/* UNSAFE SHARED STATE! */
。 - thangdc94
NULL
,那么代码应该传递什么来继续对同一字符串进行标记化? - chux - Reinstate Monica