strtok()函数

Boblim Boblim     2022-08-08     317

关键词:

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

首先看下MSDN上的解释:

char *strtok( char *strToken, const char *strDelimit );

Parameters

strToken

String containing token or tokens.

strDelimit

Set of delimiter characters.

Return Value

Returns a pointer to the next token found in strToken. They return NULL when no more tokens are found. Each call modifies strToken by substituting a NULL character for each delimiter that is encountered.

Remarks

The strtok function finds the next token in strToken. The set of characters in strDelimitspecifies possible delimiters of the token to be found in strToken on the current call.

Security Note    These functions incur a potential threat brought about by a buffer overrun problem. Buffer overrun problems are a frequent method of system attack, resulting in an unwarranted elevation of privilege. For more information, see Avoiding Buffer Overruns.

On the first call to strtok, the function skips leading delimiters and returns a pointer to the first token in strToken, terminating the token with a null character. More tokens can be broken out of the remainder of strToken by a series of calls to strtok. Each call tostrtok modifies strToken by inserting a null character after the token returned by that call. To read the next token from strToken, call strtok with a NULL value for the strTokenargument. The NULL strToken argument causes strtok to search for the next token in the modified strToken. The strDelimit argument can take any value from one call to the next so that the set of delimiters may vary.

Note   Each function uses a static variable for parsing the string into tokens. If multiple or simultaneous calls are made to the same function, a high potential for data corruption and inaccurate results exists. Therefore, do not attempt to call the same function simultaneously for different strings and be aware of calling one of these functions from within a loop where another routine may be called that uses the same function. However, calling this function simultaneously from multiple threads does not have undesirable effects.

很晕吧? 呵呵。。。

简单的说,就是函数返回第一个分隔符分隔的子串后,将第一参数设置为NULL,函数将返回剩下的子串。

下面我们来看一个例子:

 1 int main() 
 2 
 3 {
 4 
 5       char test1[] = "feng,ke,wei";  
 6 
 7       char *test2 = "feng,ke,wei";  
 8 
 9       char *p;  
10 
11       p = strtok(test1, ",");
12 
13       while(p)  
14 
15           {   
16 
17               printf("%s
", p);   
18 
19               p = strtok(NULL, ",");     
20 
21           }      
22 
23       return 0;
24 
25  }
26 
27 运行结果:
28 
29 feng
30 
31 ke
32 
33 wei

 

说明:

函数strtok将字符串分解为一系列标记(token),标记就是一系列用分隔符(delimiting chracter,通常是空格或标点符号)分开的字符。注意,此的标记是由delim分割符分割的字符串喔。

例如,在一行文本中,每个单词可以作为标记,空格是分隔符。
需要多次调用strtok才能将字符串分解为标记(假设字符串中包含多个标记)。第一次调用strtok包含两个参数,即要标记化的字符串和包含用来分隔标记的字符的字符串(即分隔符)下列语句: tokenPtr = Strtok(string, " ")
tokenPtr赋给string中第一个标记的指针。strtok的第二个参数””表示string中的标记用空格分开。
函数strtok搜索string中不是分隔符(空格)的第一个字符,这是第一个标记的开头。然后函数寻找字符串中的下一个分隔符,将其换成null( w)字符,这是当前标记的终点。注意标记的开始于结束。

函数strtok保存string中标记后面的下一个字符的指针,并返回当前标记的指针。


后面再调用strtok时,第一个参数为NULL,继续将string标记化。NULL参数表示调用strtok继续从string中上次调用 strtok时保存的位置开始标记化。

如果调用strtok时已经没有标记,则strtok返回NULL注意strtok修改输入字符串,因此,如果调用strtok之后还要在程序中使用这个字符串,则应复制这个字 符串。

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

  1 /***
  2 
  3 *strtok.c - tokenize a string with given delimiters
  4 
  5 *
  6 
  7 *       Copyright (c) Microsoft Corporation. All rights reserved.
  8 
  9 *
 10 
 11 *Purpose:
 12 
 13 *       defines strtok() - breaks string into series of token
 14 
 15 *       via repeated calls.
 16 
 17 *
 18 
 19 *******************************************************************************/
 20 
 21 #include
 22 
 23 #include
 24 
 25 #ifdef _MT
 26 
 27 #include
 28 
 29 #endif  /* _MT */
 30 
 31 /***
 32 
 33 *char *strtok(string, control) - tokenize string with delimiter in control
 34 
 35 *
 36 
 37 *Purpose:
 38 
 39 *       strtok considers the string to consist of a sequence of zero or more
 40 
 41 *       text tokens separated by spans of one or more control chars. the first
 42 
 43 *       call, with string specified, returns a pointer to the first char of the
 44 
 45 *       first token, and will write a null char into string immediately
 46 
 47 *       following the returned token. subsequent calls with zero for the first
 48 
 49 *       argument (string) will work thru the string until no tokens remain. the
 50 
 51 *       control string may be different from call to call. when no tokens remain
 52 
 53 *       in string a NULL pointer is returned. remember the control chars with a
 54 
 55 *       bit map, one bit per ascii char. the null char is always a control char.
 56 
 57 *       //这里已经说得很详细了!!比MSDN都好!
 58 
 59 *Entry:
 60 
 61 *       char *string - string to tokenize, or NULL to get next token
 62 
 63 *       char *control - string of characters to use as delimiters
 64 
 65 *
 66 
 67 *Exit:
 68 
 69 *       returns pointer to first token in string, or if string
 70 
 71 *       was NULL, to next token
 72 
 73 *       returns NULL when no more tokens remain.
 74 
 75 *
 76 
 77 *Uses:
 78 
 79 *
 80 
 81 *Exceptions:
 82 
 83 *
 84 
 85 *******************************************************************************/
 86 
 87 char * __cdecl strtok (
 88 
 89         char * string,
 90 
 91         const char * control
 92 
 93         )
 94 
 95 {
 96 
 97         unsigned char *str;
 98 
 99         const unsigned char *ctrl = control;
100 
101         unsigned char map[32];
102 
103         int count;
104 
105 #ifdef _MT
106 
107         _ptiddata ptd = _getptd();
108 
109 #else  /* _MT */
110 
111         static char *nextoken;                        //保存剩余子串的静态变量   
112 
113 #endif  /* _MT */
114 
115         /* Clear control map */
116 
117         for (count = 0; count < 32; count++)
118 
119                 map[count] = 0;
120 
121         /* Set bits in delimiter table */
122 
123         do {
124 
125                 map[*ctrl >> 3] |= (1 << (*ctrl & 7));
126 
127         } while (*ctrl++);
128 
129         /* Initialize str. If string is NULL, set str to the saved
130 
131          * pointer (i.e., continue breaking tokens out of the string
132 
133          * from the last strtok call) */
134 
135         if (string)
136 
137                 str = string;                             //第一次调用函数所用到的原串       
138 
139 else
140 
141 #ifdef _MT
142 
143                 str = ptd->_token;
144 
145 #else  /* _MT */
146 
147                 str = nextoken;                      //将函数第一参数设置为NULL时调用的余串
148 
149 #endif  /* _MT */
150 
151   /* Find beginning of token (skip over leading delimiters). Note that
152          * there is no token iff this loop sets str to point to the terminal
153          * null (*str == ‘‘) */
154         while ( (map[*str >> 3] & (1 << (*str & 7))) && *str )
155                 str++;
156         string = str;                                  //此时的string返回余串的执行结果 
157         /* Find the end of the token. If it is not the end of the string,
158          * put a null there. */
159 //这里就是处理的核心了, 找到分隔符,并将其设置为‘‘,当然‘‘也将保存在返回的串中
160         for ( ; *str ; str++ )
161                 if ( map[*str >> 3] & (1 << (*str & 7)) ) {
162                         *str++ = ;              //这里就相当于修改了串的内容 ①
163                         break;
164                 }
165         /* Update nextoken (or the corresponding field in the per-thread data
166          * structure */
167 #ifdef _MT
168         ptd->_token = str;
169 #else  /* _MT */
170         nextoken = str;                 //将余串保存在静态变量中,以便下次调用
171 #endif  /* _MT */
172         /* Determine if a token has been found. */
173         if ( string == str )
174               return NULL;
175         else
176                 return string;
177 }

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

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

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

函数内部还是不要使用strtok()

...个小时没找到原因。在吃饭的时候,突然想起可能是 strtok()引起的,查找调用的函数,果然发现在函数中使用了 strtok()。而现在的问题就是在另一段代码中先使用了 strtok(),然后在没有结束前,又调用了一个内部使用&n... 查看详情

strtok函数

1#include<stdio.h>2#include<string.h>34intmain()5{6chara[100]="aa_vfb_wffwk_fth_nnn";7char*s;//定义一个char的指针变量8s=strtok(a,"_");//strtok函数分割字符串910while(s)11{12printf("%s ",s);13s=strtok(NULL 查看详情

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

...://astute11.blog.51cto.com/4404646/1334199(一)中已经介绍了使用strtok函数的一些注意事项,本篇将介绍strtok的一个应用并引出strtok_r函数。 1.一个应用实例网络上一个比较经典的例子是将字符串切分,存入结构体中。如,现有结构... 查看详情

strtok()函数(代码片段)

说明(1)当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为 查看详情

字符串分割函数strtok(线程不安全),线程安全函数strtok_r

strtok_r函数---字符串分割函数函数原型:    char*strtok_r(char*str,constchar*delim,char**saveptr);参数:str:被分割的字符串,若str为NULL,则被分割的字符串为*saveptrdelim:依据此字符串分割strsaveptr:分割后剩余部分的字符串... 查看详情

strtok函数怎么用啊?

...考技术A其实你输入的是一个字符串,然后程序对输入用strtok解析得到各个坐标对字符串src="n1,n2,n3,n4"的解析如下char*p;intx1,x2,y1.y2;p=strtok(src,",");x1=atoi(p);p=strtok(NULL,",");x2=atoi(p);p=strtok(NULL,",");y1=atoi(p);p=... 查看详情

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

本文转载自:http://astute11.blog.51cto.com/4404646/1334198strtok函数的使用是一个老生常谈的问题了。该函数的作用很大,争议也很大。以下的表述可能与一些资料有区别或者说与你原来的认识有差异,因此,我尽量以实验为证。交代一... 查看详情

strtok函数的使用注意事项

1.函数原型及其基本应用   strtok函数是用来分解字符串的,其原型是: [cpp] viewplain copy char *strtok(char str[], const char *delim);    其中str是要分解的字符 查看详情

c语言源码剖析与实现——strtok()系列函数实现(代码片段)

文章目录源码剖析与实践strtok()源代码实现源代码用的另外几个函数strspn()、strpbrk()、strcspn()strspn()strcspn()strpbrk()strtok_r()源代码实现(不依赖其他函数库)完全自己实现strtok()设计方案代码实现性能分析测试用例源码剖析与实践strtok(... 查看详情

c语言的split字符串分割(函数strtok)(代码片段)

1、说明:在C语言中实现对字符串的分割(多亏了strtok函数)2、案例讲解1、Strtok()函数详解:该函数包含在"string.h"头文件中1)函数原型:char*strtok(char*str,constchar*delimiters);2)函数功能:切割... 查看详情

c语言最短时间带你实现strtok,字符串分割函数,建议收藏!!!(代码片段)

strtok前言一、strtok的基本使用二、strtok的实现总结↗️↗️↗️建议三连,以防丢失前言字符串分割函数strtok,大家可能都知道他怎么使用,一旦要用的时候就会心生疑惑,不知道它的内部的实现,废话不多... 查看详情

strtok/atoi/atof/atol函数用法详解(代码片段)

 char*strtok(char*str,char*delim)str不能是const类型,因为此方法会导致原字符串的修改delim中每一个字符都为分隔符,而不支持"分割串"的概念分割本质:匹配到后,将char*位置字符替换为 查看详情

为啥当我使用不同版本的 GCC 时使用 strtok 函数时出现此错误?

】为啥当我使用不同版本的GCC时使用strtok函数时出现此错误?【英文标题】:WhyisthiserroronusingstrtokfunctionshowingwhenIuseadifferentversionofGCC?为什么当我使用不同版本的GCC时使用strtok函数时出现此错误?【发布时间】:2020-08-2823:56:54【... 查看详情

strtok()出现segmentfault的错误(代码片段)

...的命令通过空格分割成一个个字符串参数,这里我使用了strtok()函数,然后遇到了segmentfault的错误。出现问题的代码如下:终于寻找到原因:strtok(char*string,char*delim)函数的实现逻辑是函数是在s中查找包含在delim中的字符并用NULL(... 查看详情

strtok的使用(代码片段)

/*strtok函数的使用*/#include<stdio.h>#include<stdlib.h>#include<string.h>//函数原型://char*strtok(char*str,constchar*delim)//参数://str--要被分解成一组小字符串的字符串//delim--包含分隔符的C字符串//返回值//该函数返回被分解的第一... 查看详情

字符串分割strtok_s(代码片段)

https://blog.csdn.net/hustfoxy/article/details/23473805/ 1)、strtok函数函数原型:char*strtok(char*str,constchar*delimiters);   参数:str,待分割的字符串(c-string);delimiters,分割符字符串。该函数用来将字符串分割成一个个片段。参... 查看详情

VC7 中的 strtok_s 等价物是啥?

】VC7中的strtok_s等价物是啥?【英文标题】:Whatisthestrtok_sequivalentinVC7?VC7中的strtok_s等价物是什么?【发布时间】:2008-11-2100:10:04【问题描述】:strtok_s函数存在于vc8中,但不存在于vc7中。那么,在vc7中,什么是相当于strtok_s的函... 查看详情

字符串库函数及重点函数的模拟实现下篇---strstr+strtok+strerror(代码片段)

本文重点8.strstr9.strtok10.strerror本文将继续介绍字符串库函数,即重点函数的模拟实现。正文开始@边通书8.strstr💛字符串查找函数—在一个字符串中,查找子字符串strstr的使用:😇strstr的模拟实现my_strlenÿ... 查看详情