关于strtok函数【转】

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,函数将返回剩下的子串。

下面我们来看一个例子:

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 0;

}

运行结果:

feng

ke

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, ",")则会出现内存错误,这是为什么呢?是不是跟它里面那个静态变量有关呢? 我们来看看它的原码:

/***

*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

关于strtok函数【转】

时间: 2024-07-29 19:11:35

关于strtok函数【转】的相关文章

Hdu 1106 排序 (atoi函数与 strtok函数的应用

链接: http://acm.hdu.edu.cn/showproblem.php?pid=1106 好久都没刷题了,今天突然特别怀念以前刷题的日子,所以就找了几道水题来做做~~呵呵 在写这篇博客之前呢,已经很明了自己已经大三了,时光匆忙,在还没来得及转过头来,就已经过了两年了大学,原来走了这么远了~~感觉再怎么样,大三还是不敢偷懒~~不过有时候还真是挺迷茫的说实话,在这里呢,真心希望能得到你们各位的建议,只要是对我未来就业有好处的,我都会虚心取纳,(BTW:我是学嵌入式方向的)万分感谢~~~

用strtok函数分割字符串

用strtok函数分割字符串 需要在loadrunner里面获得“15”(下面红色高亮的部分),并做成关联参数. //Body response 内容: <BODY><; PRE>//OK[8,7,5,15,6,5,0,4,0,3,0,3,2,0,0,0,1 用web_reg_save_param取出“8,7,5,15,6,5,0,4,0,3,0,3,2,0,0,0,1”这一段,然后用strtok函数切割出一个个数字,第四个数字就是要找的值 例如: extern char * st

strtok函数的使用与实现

一个用来分割字符串的函数: strtok 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

strtok函数

strtok函数是cstring文件里的函数 strtok函数是cstring文件里的函数 其功能是截断字符串 原型为:char *strtok(char s[],const char *delin); s[]是要截断的字符串,delin是用来截断的字符串. 每次调用成功后则返回切割出片段的指针. 比如,strtok("aaa,sa",",");第一次运行就会返回','之前的aaa #include<iostream> #include<cstri

strtok函数的简单应用 hdu 1106

排序 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 38231    Accepted Submission(s): 10832 Problem Description 输入一行数字,如果我们把这行数字中的'5'都看成空格,那么就得到一行用空格分割的若干非负整数(可能有些整数以'0'开头,这些头部的'0'应该被忽略掉,除非这个整数就是

strtok函数读写冲突问题

先上测试代码 #include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const char* split = ";"; char* str = "Hello;world;"; //result = NULL; char* result = strtok(str, split); cout &l

C++中关于strtok()函数的用法

strtok: #include <string.h> char *strtok(char *str, const char *delim); char *strtok_r(char *str, const char *delim, char **saveptr); 功能:分解字符串为一组标记串.str为要分解的字符串,delim为分隔符字符串. 说明:首次调用时,str必须指向要分解的字符串,随后调用要把s设成NULL. strtok在str中查找包含在delim中的字符并用NULL('/0

strtok()函数

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 tok

C语言strtok()函数:字符串分割

头文件:#include <string.h> 定义函数:char * strtok(char *s, const char *delim); 函数说明:strtok()用来将字符串分割成一个个片段.参数s 指向欲分割的字符串,参数delim 则为分割字符串,当strtok()在参数s 的字符串中发现到参数delim 的分割字符时则会将该字符改为\0 字符.在第一次调用时,strtok()必需给予参数s 字符串,往后的调用则将参数s 设置成NULL.每次调用成功则返回下一个分割后的字符串指针.