CSDN中的解释
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,函数将返回剩下的子串。例子:
#include<string.h> #include<stdio.h> int main() { char test[] = "feng,ke,wei"; char *p; p = strtok(test, ","); while(p) { printf("%s\n", p); p = strtok(NULL, ","); } return 0; }输出:
2、strtok_s函数
strtok_s是windows下的一个分割字符串安全函数,其函数原型如下:
char *strtok_s( char *strToken, const char *strDelimit, char **buf);
这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。
3、strtok_r函数
strtok_s函数是linux下分割字符串的安全函数,函数声明如下:
char *strtok_r(char *str, const char *delim, char **saveptr);
该函数也会破坏带分解字符串的完整性,但是其将剩余的字符串保存在saveptr变量中,保证了安全性。