C语⾔分割字符串函数strtok 在编程过程中,有时需要对字符串进⾏分割.⽽有效使⽤这些字符串分隔函数将会给我们带来很多的便利.下⾯我将在MSDN中学到的strtok函数做如下翻译.
strtok :在⼀个字符串查下⼀个符号
char *strtok( char *strToken, const char *strDelimit );
返回值:返回指向在strToken字符串到的下⼀个符号的指针,当在字符串不到符号时,将返回NULL.每次调⽤都通过⽤NULL字符替代在strToken字符串遇到的分隔符来修改strToken字符串.
参数:
strToken:包含符号的字符串
strDelimit:分隔符集合
注:第⼀次调⽤strtok函数时,这个函数将忽略间距分隔符并返回指向在strToken字符串到的第⼀个符号的指针,该符号后以NULL字符结尾.通过调⽤⼀系列的strtok函数,更多的符号将从strToken字符串中分离出来.每次调⽤strtok函数时,都将通过在到的符号后插⼊⼀个NULL字符来修改strToken字符串.为了读取strToken中的下⼀个符号,调⽤strtok函数时strToken参数为NULL,这会引发strtok函数在已修改过
的strToken字符串查下⼀个符号.
Example(摘⾃MSDN)
/* STRTOK.C: In this program, a loop uses strtok
* to print all the tokens (separated by commas
* or blanks) in the string named "string".
*/
#include <string.h>
#include <stdio.h>
char string[] = "A string\tof ,,tokens\nand some  more tokens";
字符串复制函数char seps[]  = " ,\t\n";
char *token;
void main( void )
{
printf( "%s\n\nTokens:\n", string );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
Output
A string  of ,,tokens
and some  more tokens
Tokens:
A
string
of
tokens
and
some
more
tokens