转:strtok:
用法:token = strtok(source-str,seperator-str)
用途:在source-str中找出以seperator-str中的字符为分隔的字符串,即是源串中除去了含有分隔串中的所有字符后余下的一段段的字符串,每调用一次找到一串,找不到则返回空串。
注意:返回值是指向源串的指针,所以同样要保证源串的有效性,此外,每次调用返回找到的子串的时候都会把源串中该子串的尾部字符(原来是搜索串中的某一字符)修改成'/0'字符。还有一个要注意的是,这个函数使用全局的静态缓冲区(函数自己的静态buffer),所以在某一个线程里不要同时调用这个函数来处理两个字符串,否则极易出现不正常的结果,正确的处理方法是先找出一个字符串中的所有子串,然后才转到处理另一个字符串。多线程之间则不会出现这种干扰。
同样举MSDN中的例子:
数据准备:
char string[] = "A string/tof ,,tokens/nand some more tokens";
char seps[] = " ,/t/n";
char *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 );
/*注意到上面这个NULL,它表明的是从上次调用结果中strtok自有的缓冲区中继续取出余下的子串*/
}
显示结果:
A //此时string[1]='/0',原先为空格
string
of
tokens
and
some
more
tokens
自己的实验程序:
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
int main()
{
char string[] = "A string of ,,tokens%and some more tokens";
char seps[] = " %/n";
char *token;
token = strtok( string, seps );
while( token != NULL )
{
printf( " %s/n", token );
token = strtok( NULL, seps );
}
return 0;
}