Chinaunix首页 | 论坛 | 博客
  • 博客访问: 392360
  • 博文数量: 103
  • 博客积分: 3073
  • 博客等级: 中校
  • 技术积分: 1078
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-23 15:04
文章分类

全部博文(103)

文章存档

2012年(13)

2011年(76)

2010年(14)

分类: LINUX

2011-08-17 11:06:15

function
char * strtok ( char * str, const char * delimiters );

Split string into tokens

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

第一次调用时第一个参数使用的是string的指针
第二次及后续的调用使用的是null作为参数


strtok实现过程中,使用某个静态变量来记录分析的str的位置。
陷阱:strtok 对参数进行了修改,在delimeter的位置换成了 \0 。
           忽略了这一点,调了半天的bug.

  1. char * __cdecl strtok(char *s1, const char *delimit)
  2. {
  3.     static char *lastToken = NULL; /* UNSAFE SHARED */
  4.     char *tmp;

  5.     /* Skip leading delimiters if new string. */
  6.     if ( s1 == NULL ) {
  7.         s1 = lastToken;
  8.         if (s1 == NULL) /* End of story? */
  9.             return NULL;
  10.     } else {
  11.         s1 += strspn(s1, delimit);
  12.     }

  13.     /* Find end of segment */
  14.     tmp = strpbrk(s1, delimit);
  15.     if (tmp) {
  16.         /* Found another delimiter, split string and save state. */
  17.         *tmp = '\0';
  18.         lastToken = tmp + 1;
  19.     } else {
  20.         /* Last segment, remember that. */
  21.         lastToken = NULL;
  22.     }

  23.     return s1;
  24. }

  1. #include <sys/cdefs.h>
  2. #include <string.h>

  3. /*
  4.  * Span the string s2 (skip characters that are in s2).
  5.  */
  6. size_t
  7. strspn(s1, s2)
  8.     const char *s1;
  9.     register const char *s2;
  10. {
  11.     register const char *p = s1, *spanp;
  12.     register char c, sc;

  13.     /*
  14.      * Skip any characters in s2, excluding the terminating \0.
  15.      */
  16. cont:
  17.     c = *p++;
  18.     for (spanp = s2; (sc = *spanp++) != 0;)
  19.         if (sc == c)
  20.             goto cont;
  21.     return (p - 1 - s1);
  22. }

  1. #include <sys/cdefs.h>
  2. #include <string.h>

  3. /*
  4.  * Find the first occurrence in s1 of a character in s2 (excluding NUL).
  5.  */
  6. char *
  7. strpbrk(s1, s2)
  8.     register const char *s1, *s2;
  9. {
  10.     register const char *scanp;
  11.     register int c, sc;

  12.     while ((c = *s1++) != 0) {
  13.         for (scanp = s2; (sc = *scanp++) != 0;)
  14.             if (sc == c)
  15.                 return ((char *)(s1 - 1));
  16.     }
  17.     return (NULL);
  18. }

阅读(613) | 评论(0) | 转发(0) |
0

上一篇:Nehalem 流水线

下一篇:string : c

给主人留下些什么吧!~~