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 );*
对 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 值,则会要求继续标记与以前相同的内容。
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取