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

前端之家收集整理的这篇文章主要介绍了c – strtok() – 为什么必须传递NULL指针才能获取字符串中的下一个标记?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是对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 argument,in order to get the next token in the
string.

但是我不知道,为什么你必须传递NULL指针才能获得字符串中的下一个标记.我搜索了大约15分钟,但没有在互联网上找到解释.

解决方法

strtok()将静态变量中的一些数据保存在函数本身内,以便它可以继续从之前的调用离开它的点进行搜索.要发送要保持搜索同一个字符串的strtok(),您将传递一个NULL指针作为其第一个参数. strtok()检查它是否为NULL,如果是,则使用其当前存储的数据.如果第一个参数不为空,则将其视为新搜索,并重置所有内部数据.

也许最好的事情是搜索strtok()函数的实际实现.我已经发现一个小到这里发布,所以你了解如何处理这个NULL参数:

  1. /* Copyright (c) Microsoft Corporation. All rights reserved. */
  2.  
  3. #include <string.h>
  4.  
  5. /* ISO/IEC 9899 7.11.5.8 strtok. DEPRECATED.
  6. * Split string into tokens,and return one at a time while retaining state
  7. * internally.
  8. *
  9. * WARNING: Only one set of state is held and this means that the
  10. * WARNING: function is not thread-safe nor safe for multiple uses within
  11. * WARNING: one thread.
  12. *
  13. * NOTE: No library may call this function.
  14. */
  15.  
  16. char * __cdecl strtok(char *s1,const char *delimit)
  17. {
  18. static char *lastToken = NULL; /* UNSAFE SHARED STATE! */
  19. char *tmp;
  20.  
  21. /* Skip leading delimiters if new string. */
  22. if ( s1 == NULL ) {
  23. s1 = lastToken;
  24. if (s1 == NULL) /* End of story? */
  25. return NULL;
  26. } else {
  27. s1 += strspn(s1,delimit);
  28. }
  29.  
  30. /* Find end of segment */
  31. tmp = strpbrk(s1,delimit);
  32. if (tmp) {
  33. /* Found another delimiter,split string and save state. */
  34. *tmp = '\0';
  35. lastToken = tmp + 1;
  36. } else {
  37. /* Last segment,remember that. */
  38. lastToken = NULL;
  39. }
  40.  
  41. return s1;
  42. }

猜你在找的C&C++相关文章