下面的说明摘自于最新的Linux内核2.6.29,说明了strtok()这个函数已经不再使用,由速度更快的strsep()代替

/*
* linux/lib/string.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* stupid library routines.. The optimized versions should generally be found
* as inline code in <asm-xx/string.h>
*
* These are buggy as well..
*
* * Fri Jun 25 1999, Ingo Oeser <ioe@informatik.tu-chemnitz.de>
* - Added strsep() which will replace strtok() soon (because strsep() is
* reentrant and should be faster). Use only strsep() in new code, please.
*
* * Sat Feb 09 2002, Jason Thomas <jason@topic.com.au>,
* Matthew Hawkins <matt@mh.dropbear.id.au>
* - Kissed strtok() goodbye
*/

strtok()这个函数大家都应该碰到过,但好像总有些问题, 这里着重讲下它

下面我们来看一个例子:

 int main() {

     char test1[] = "feng,ke,wei";

     char *test2 = "feng,ke,wei";

     char *p; p = strtok(test1, ",");

     while(p)

     {   

         printf("%s\n", p);   

         p = strtok(NULL, ",");   

     }

     return ;

 }

运行结果:

feng

ke

wei

但如果用p = strtok(test2, ",")则会出现内存错误,这是为什么呢?是不是跟它里面那个静态变量有关呢? 我们来看看它的原码:

/***
*strtok.c - tokenize a string with given delimiters
*
*       Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
*       defines strtok() - breaks string into series of token
*       via repeated calls.
*
*******************************************************************************/
#include <cruntime.h>
#include <string.h>
#ifdef _MT
#include <mtdll.h>
#endif /* _MT */
/***
*char *strtok(string, control) - tokenize string with delimiter in control
*
*Purpose:
*       strtok considers the string to consist of a sequence of zero or more
*       text tokens separated by spans of one or more control chars. the first
*       call, with string specified, returns a pointer to the first char of the
*       first token, and will write a null char into string immediately
*       following the returned token. subsequent calls with zero for the first
*       argument (string) will work thru the string until no tokens remain. the
*       control string may be different from call to call. when no tokens remain
*       in string a NULL pointer is returned. remember the control chars with a
*       bit map, one bit per ascii char. the null char is always a control char.
*       //这里已经说得很详细了!!比MSDN都好!
*Entry:
*       char *string - string to tokenize, or NULL to get next token
*       char *control - string of characters to use as delimiters
*
*Exit:
*       returns pointer to first token in string, or if string
*       was NULL, to next token
*       returns NULL when no more tokens remain.
*
*Uses:
*
*Exceptions:
*
*******************************************************************************/
char * __cdecl strtok (
        char * string,
        const char * control
        )
{
        unsigned char *str;
        const unsigned char *ctrl = control;
          unsigned char map[32];
        int count;
#ifdef _MT
        _ptiddata ptd = _getptd();
#else /* _MT */
        static char *nextoken;                       //保存剩余子串的静态变量   
#endif /* _MT */
          /* Clear control map */
        for (count = 0; count < 32; count++)
                map[count] = 0;
          /* Set bits in delimiter table */
        do {
                map[*ctrl >> 3] |= (1 << (*ctrl & 7));
        } while (*ctrl++);
          /* Initialize str. If string is NULL, set str to the saved
         * pointer (i.e., continue breaking tokens out of the string
         * from the last strtok call) */
        if (string)
                str = string;                             //第一次调用函数所用到的原串       
else
#ifdef _MT
                str = ptd->_token;
#else /* _MT */
               str = nextoken;                      //将函数第一参数设置为NULL时调用的余串
#endif  /* _MT */
          /* Find beginning of token (skip over leading delimiters). Note that
         * there is no token iff this loop sets str to point to the terminal
         * null (*str == '\0') */
        while ( (map[*str >> 3] & (1 << (*str & 7))) && *str )
                str++;
        string = str;                                    //此时的string返回余串的执行结果 
          /* Find the end of the token. If it is not the end of the string,
         * put a null there. */
//这里就是处理的核心了, 找到分隔符,并将其设置为'\0',当然'\0'也将保存在返回的串中
        for ( ; *str ; str++ )
                if ( map[*str >> 3] & (1 << (*str & 7)) ) {
                        *str++ = '\0';              //这里就相当于修改了串的内容 ①
                        break;
                }
          /* Update nextoken (or the corresponding field in the per-thread data
         * structure */
#ifdef _MT
        ptd->_token = str;
#else /* _MT */
        nextoken = str;                 //将余串保存在静态变量中,以便下次调用
#endif /* _MT */
          /* Determine if a token has been found. */
        if ( string == str )
               return NULL;
        else
                return string; 1. strtok介绍 众所周知,strtok可以根据用户所提供的分割符(同时分隔符也可以为复数比如“,。”) 将一段字符串分割直到遇到"\0". 比如,分隔符=“,” 字符串=“Fred,John,Ann” 通过strtok 就可以把3个字符串 “Fred”     “John”      “Ann”提取出来。 上面的C代码为
QUOTE:
int in=0;
char buffer[]="Fred,John,Ann"
char *p[3];
char *buff = buffer;
while((p[in]=strtok(buf,","))!=NULL) {
i++;
buf=NULL; }

如上代码,第一次执行strtok需要以目标字符串的地址为第一参数(buf=buffer),之后strtok需要以NULL为第一参数 (buf=NULL)。指针列p[],则储存了分割后的结果,p[0]="John",p[1]="John",p[2]="Ann",而buf就变 成    Fred\0John\0Ann\0。

2. strtok的弱点
让我们更改一下我们的计划:我们有一段字符串 "Fred male 25,John male 62,Anna female 16" 我们希望把这个字符串整理输入到一个struct,

QUOTE:
struct person { 
char [25] name ; 
char [6] sex;
char [4] age;
}

要做到这个,其中一个方法就是先提取一段被“,”分割的字符串,然后再将其以“ ”(空格)分割。
比如: 截取 "Fred male 25" 然后分割成 "Fred" "male" "25"
以下我写了个小程序去表现这个过程:

 #include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
int in=;
char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
char *p[];
char *buf=buffer; while((p[in]=strtok(buf,","))!=NULL) {
buf=p[in];
while((p[in]=strtok(buf," "))!=NULL) {
in++;
buf=NULL;
}
p[in++]="***"; //表现分割
buf=NULL; } printf("Here we have %d strings\n",i);
for (int j=; j<in; j++)
printf(">%s<\n",p[j]);
return ;
}

这个程序输出为:
Here we have 4 strings
>Fred<
>male<
>25<
>***<
这只是一小段的数据,并不是我们需要的。但这是为什么呢? 这是因为strtok使用一个static(静态)指针来操作数据,让我来分析一下以上代码的运行过程:

红色为strtok的内置指针指向的位置,蓝色为strtok对字符串的修改

1. "Fred male 25,John male 62,Anna female 16" //外循环

2. "Fred male 25\0John male 62,Anna female 16" //进入内循环

3.    "Fred\0male 25\0John male 62,Anna female 16"

4.    "Fred\0male\05\0John male 62,Anna female 16"

5 "Fred\0male\025\0John male 62,Anna female 16" //内循环遇到"\0"回到外循环

6   "Fred\0male\025\0John male 62,Anna female 16" //外循环遇到"\0"运行结束。

3. 使用strtok_r
在这种情况我们应该使用strtok_r, strtok reentrant. 
char *strtok_r(char *s, const char *delim, char **ptrptr);

相对strtok我们需要为strtok提供一个指针来操作,而不是像strtok使用配套的指针。
代码:

QUOTE:
 #include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
int in=;
char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
char *p[];
char *buf=buffer; char *outer_ptr=NULL;
char *inner_ptr=NULL; while((p[in]=strtok_r(buf,",",&outer_ptr))!=NULL) {
buf=p[in];
while((p[in]=strtok_r(buf," ",&inner_ptr))!=NULL) {
in++;
buf=NULL;
}
p[in++]="***";
buf=NULL; } printf("Here we have %d strings\n",i);
for (int j=; jn<i; j++)
printf(">%s<\n",p[j]);
return ;
}

这一次的输出为:
Here we have 12 strings
>Fred<
>male<
>25<
>***<
>John<
>male<
>62<
>***<
>Anna<
>female<
>16<
>***<

让我来分析一下以上代码的运行过程:

红色为strtok_r的outer_ptr指向的位置,
紫色为strtok_r的inner_ptr指向的位置,
蓝色为strtok对字符串的修改

1. "Fred male 25,John male 62,Anna female 16" //外循环

2. "Fred male 25\0John male 62,Anna female 16"//进入内循环

3.   "Fred\0male 25\0John male 62,Anna female 16"

4   "Fred\0male\05\0John male 62,Anna female 16"

5 "Fred\0male\025\0John male 62,Anna female 16" //内循环遇到"\0"回到外循环

6   "Fred\0male\025\0John male 62\0Anna female 16"//进入内循环

}

原来, 该函数修改了原串.

所以,当使用char *test2 = "feng,ke,wei"作为第一个参数传入时,在位置①处, 由于test2指向的内容保存在文字常量区,该区的内容是不能修改的,所以会出现内存错误. 而char test1[] = "feng,ke,wei" 中的test1指向的内容是保存在栈区的,所以可以修改.

看到这里 大家应该会对文字常量区有个更加理性的认识吧.....

补充:其实在使用strtok_r函数的时候,只需声明两个char类型的指针outer_ptr,inner_ptr当做函数的第三个参数即可;

例:

解析URL中的路径和查询字符串。例如:http://www.google.cn/search?complete=1&hl=zh-CN&ie=GB2312&q=linux&meta=

 #include <stdio.h>
#include <string.h> #define MAX_STR 200 void strtok_r_text()
{
char value[MAX_STR] = "http://www.google.cn/search?complete=1&hl=zh-CN&ie=GB2312&q=linux&meta="; //char value[MAX_STR] = "tom&math&120?jim&math&110";
char *str;
char *buf = value; char *one_ptr = NULL;
char *two_ptr = NULL;
char *three_ptr = NULL; while((str = strtok_r(buf,"?",&one_ptr)) != NULL)
{
buf = str;
while((str = strtok_r(buf,"&",&two_ptr)) != NULL)
{
buf = str;
while((str = strtok_r(buf,"=",&three_ptr)) != NULL)
{
puts(str);
buf = NULL;
}
buf = NULL;
}
buf = NULL; }
} int main(void)
{
strtok_r_text();
return ;
}  

此时就会按照预想的结果把截取的字符串输出了!

【C】——strtok()和strtok_r()的更多相关文章

  1. [转]关于strtok和strtok_r函数的深度研究

    在linux环境下,字符串分割的函数中,大家比较常用的是strtok函数,这个函数用处很大,但也有一些问题,以下将深度挖掘一下这个函数的用法,原理,实现,其次,该函数是不可再入函数,但是在linux ...

  2. 关于函数strtok和strtok_r的使用要点和实现原理(二)

    http://www.cnblogs.com/stemon/p/4013264.html已经介绍了使用strtok函数的一些注意事项,本篇将介绍strtok的一个应用并引出strtok_r函数. 1. ...

  3. 关于函数strtok和strtok_r的使用要点和实现原理(二)【转】

    本文转载自:http://astute11.blog.51cto.com/4404646/1334199 (一)中已经介绍了使用strtok函数的一些注意事项,本篇将介绍strtok的一个应用并引出s ...

  4. 关于函数strtok和strtok_r的使用要点和实现原理

    strtok函数的使用是一个老生常谈的问题了.该函数的作用很大,争议也很大.以下的表述可能与一些资料有区别或者说与你原来的认识有差异,因此,我尽量以实验为证.交代一下实验环境是必要的,winxp+vc ...

  5. strtok和strtok_r

    1.strtok()函数的用法 函数原型:char *strtok(char *s, const char *delim); Function:分解字符串为一组字符串.s为要分解的字符串,delim为 ...

  6. 关于函数strtok和strtok_r的使用要点和实现原理(一)【转】

    本文转载自:http://astute11.blog.51cto.com/4404646/1334198 strtok函数的使用是一个老生常谈的问题了.该函数的作用很大,争议也很大.以下的表述可能与一 ...

  7. 字符串分割函数 STRTOK & STRTOK_R (转)

    1.一个应用实例 网络上一个比较经典的例子是将字符串切分,存入结构体中.如,现有结构体 typedef struct person{     char name[25];     char sex[1 ...

  8. STRTOK函数和STRTOK_R函数

    STRTOK函数和STRTOK_R函数 注:本文转载自博客园,感谢作者整理! 1.一个应用实例 网络上一个比较经典的例子是将字符串切分,存入结构体中.如,现有结构体 typedef struct pe ...

  9. [转载]strtok函数和strtok_r函数

    1.一个应用实例 网络上一个比较经典的例子是将字符串切分,存入结构体中.如,现有结构体 typedef struct person{     char name[25];     char sex[1 ...

随机推荐

  1. U811.1接口EAI系列之二--生成销售出库单调用U8的EAI通用处理方法--PowerBuilder语言

    1.销售系统销售出库,更新U811.1材料库存的EAI的XML生成. 2.主要根据U8配置会生成出库单和同时是否更新库存量,还是更新现存量等等. 3.具体参考代码如下: 作者:王春天 2013-11- ...

  2. Windows8.1远程桌面时提示凭据不工作的解决方案

    本人两台电脑都是win8.1.首先确认以下三点: 1.密码没有错 2.用户连接没有达到上线(只有我一个人尝试连) 3.该用户已开启远程连接 此时还说凭据不工作的原因是域的问题,因为mstsc默认使用M ...

  3. 如何改变git的默认路径

    1.win10下git默认启动路径是用户的根目录,东西太多太乱了. 2.修改很容易,右键单击桌面的快捷方式,选择“属性”. 3.删除“目录”中的 --cd-to-home 选项,再将“起始位置&quo ...

  4. Atitit  undac网络设备管理法案 (路由器 交换机等)    法案编号USRr101510

    Atitit  undac网络设备管理法案 (路由器 交换机等)    法案编号USRr101510 1.1. 版本历史1 1.2. 密码设置规范 与原则1 1.3. 如何设置密码 ,设置一个简单又安 ...

  5. centos 7 五笔安装

    # yum install ibus ibus-table-wubi 需要重启动

  6. HTML5学习笔记(二十四):DOM扩展

    DOM扩展 DOM标准扩展最开始都是来自各个浏览器的自定义扩展DOM的功能,后被收录为标准的DOM相关API. 本笔记只记录被各大浏览器支持的标准扩展,对于特定浏览器的专有扩展不讨论. 选择符API ...

  7. 2-2-求并集A=A∪B-线性表-第2章-《数据结构》课本源码-严蔚敏吴伟民版

    课本源码部分 第2章  线性表 - 求并集A=A∪B ——<数据结构>-严蔚敏.吴伟民版        ★有疑问先阅读★ 源码使用说明  链接☛☛☛ <数据结构-C语言版>(严 ...

  8. how many shards and replicas should be set for Elastic Search

    https://cpratt.co/how-many-shards-should-elasticsearch-indexes-have/ https://blog.trifork.com/2014/0 ...

  9. pandas数组(pandas Series)-(3)向量化运算

    这篇介绍下有index索引的pandas Series是如何进行向量化运算的: 1. index索引数组相同: s1 = pd.Series([1, 2, 3, 4], index=['a', 'b' ...

  10. ActionScript 3操作XML 详解

    AS3引入了E4X ,它是根据ECMAScript标准处理XML 数据的全新机制.这使得程序员在程序中无缝地操作XML.在AS3中可以使用XML字面值将XML数据直接写入代码,该字面值将被自动解析. ...