c – strtok() – 为什么必须传递NULL指针才能获取字符串中的下
发布时间:2020-12-16 05:21:52 所属栏目:百科 来源:网络整理
导读:这是对strtok()的解释. #include 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 arg
这是对strtok()的解释.
但是我不知道,为什么你必须传递NULL指针才能获得字符串中的下一个标记.我搜索了大约15分钟,但没有在互联网上找到解释. 解决方法
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 = ' '; lastToken = tmp + 1; } else { /* Last segment,remember that. */ lastToken = NULL; } return s1; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |