C/C++处理分隔符相关函数

3.strtok和strtok_r的源代码

这两个函数的实现,由众多的版本。我strtok_r来自于GNU C Library,strtok则调用了strtok_r。因此先给出strtok_r的源代码。

  1. /* 
  2.  * strtok_r.c: 
  3.  * Implementation of strtok_r for systems which don't have it. 
  4.  * 
  5.  * This is taken from the GNU C library and is distributed under the terms of 
  6.  * the LGPL. See copyright notice below. 
  7.  * 
  8.  */  
  9.   
  10. #ifdef HAVE_CONFIG_H   
  11. #include "configuration.h"   
  12. #endif /* HAVE_CONFIG_H */   
  13.   
  14. #ifndef HAVE_STRTOK_R   
  15.   
  16. static const char rcsid[] = "$Id: strtok_r.c,v 1.1 2001/04/24 14:25:34 chris Exp $";  
  17.   
  18. #include <string.h>   
  19.   
  20. #undef strtok_r   
  21.   
  22. /* Parse S into tokens separated by characters in DELIM. 
  23.    If S is NULL, the saved pointer in SAVE_PTR is used as 
  24.    the next starting point.  For example: 
  25.         char s[] = "-abc-=-def"; 
  26.         char *sp; 
  27.         x = strtok_r(s, "-", &sp);      // x = "abc", sp = "=-def" 
  28.         x = strtok_r(NULL, "-=", &sp);  // x = "def", sp = NULL 
  29.         x = strtok_r(NULL, "=", &sp);   // x = NULL 
  30.                 // s = "abc/0-def/0" 
  31. */  
  32. char *strtok_r(char *s, const char *delim, char **save_ptr) {  
  33.     char *token;  
  34.   
  35.     if (s == NULL) s = *save_ptr;  
  36.   
  37.     /* Scan leading delimiters.  */  
  38.     s += strspn(s, delim);  
  39.     if (*s == '/0')   
  40.         return NULL;  
  41.   
  42.     /* Find the end of the token.  */  
  43.     token = s;  
  44.     s = strpbrk(token, delim);  
  45.     if (s == NULL)  
  46.         /* This token finishes the string.  */  
  47.         *save_ptr = strchr(token, '/0');  
  48.     else {  
  49.         /* Terminate the token and make *SAVE_PTR point past it.  */  
  50.         *s = '/0';  
  51.         *save_ptr = s + 1;  
  52.     }  
  53.   
  54.     return token;  
  55. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值