c语言之strtok_r函数和strtok函数
来源:互联网 发布:北京it外包 编辑:程序博客网 时间:2024/06/05 16:53
c语言之strtok_r函数是linux平台下的strtok函数的线程安全版本,windows的string.h中并不包含此函数。其函数原型如下:
char *strtok_r(char *str, const char *delim, char **saveptr);
参数char **saveptr参数是一个指向char *的指针变量,用来在strtok_r内部保存切分时的上下文,以应对连续调用分解相同源字符串。
第一次调用strtok_r时,str参数必须指向待提取的字符串,saveptr参数的值可以忽略。连续调用时,str赋值为NULL,saveptr为上次调用后返回的值,不要修改。
其函数实现如下:
- /*
- * strtok_r.c:
- * Implementation of strtok_r for systems which don't have it.
- *
- * This is taken from the GNU C library and is distributed under the terms of
- * the LGPL. See copyright notice below.
- *
- */
- #ifdef HAVE_CONFIG_H
- #include "configuration.h"
- #endif /* HAVE_CONFIG_H */
- #ifndef HAVE_STRTOK_R
- static const char rcsid[] = "$Id: strtok_r.c,v 1.1 2001/04/24 14:25:34 chris Exp $";
- #include <string.h>
- #undef strtok_r
- /* Parse S into tokens separated by characters in DELIM.
- If S is NULL, the saved pointer in SAVE_PTR is used as
- the next starting point. For example:
- char s[] = "-abc-=-def";
- char *sp;
- x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
- x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
- x = strtok_r(NULL, "=", &sp); // x = NULL
- // s = "abc/0-def/0"
- */
- char *strtok_r(char *s, const char *delim, char **save_ptr) {
- char *token;
- if (s == NULL) s = *save_ptr;
- /* Scan leading delimiters. */
- s += strspn(s, delim);
- if (*s == '/0')
- return NULL;
- /* Find the end of the token. */
- token = s;
- s = strpbrk(token, delim);
- if (s == NULL)
- /* This token finishes the string. */
- *save_ptr = strchr(token, '/0');
- else {
- /* Terminate the token and make *SAVE_PTR point past it. */
- *s = '/0';
- *save_ptr = s + 1;
- }
- return token;
- }
代码整体的流程如下:
(1)判断参数s是否为NULL,如果是NULL就以传递进来的save_ptr作为起始分解位置;若不是NULL,则以s开始切分。
(2)跳过待分解字符串开始的所有分界符。
(3)判断当前待分解的位置是否为'/0',若是则返回NULL(联系到(一)中所说对返回值为NULL的解释);不是则继续。
(4)保存当前的待分解串的指针token,调用strpbrk在token中找分界符:如果找不到,则将save_ptr赋值为待分解串尾部'/0'所在的位置,token没有发生变化;若找的到则将分界符所在位置赋值为'/0',token相当于被截断了(提取出来),save_ptr指向分界符的下一位。
(5)函数的最后(无论找到还是没找到)都将返回。
阅读全文
0 0
- c语言之strtok_r函数和strtok函数
- linux C语言函数之strtok和strtok_r
- c函数: strtok 和 strtok_r
- c函数: strtok 和 strtok_r
- c函数: strtok和strtok_r
- C中strtok()函数和strtok_r()函数
- C中strtok()函数和strtok_r()函数
- C语言字符串截取函数strtok和strtok_r
- strtok和strtok_r函数
- STRTOK函数和STRTOK_R函数
- STRTOK函数和STRTOK_R函数
- strtok函数和strtok_r函数
- STRTOK函数和STRTOK_R函数
- strtok函数和strtok_r函数
- strtok函数和strtok_r函数
- STRTOK函数和STRTOK_R函数
- strtok函数和strtok_r函数
- strtok()和strtok_r() 函数解析
- JAVA基础学习_方法
- tcp keepalive
- Eclipse中配置maven
- 11.2.0.4 oracle_rac 升级PSU 11.2.0.4.17
- Piotr's Ants UVA
- c语言之strtok_r函数和strtok函数
- 计算机基础知识
- C++ Primer Plus 第四章课后编程练习
- course 系统
- BeanUtils.populate的作用
- 图像特效之老照片
- ubuntu下latex的使用
- 宏以及#define;enum;comst的区别
- JAVA 8函数式编程(六):怎样复用Stream对象