您的位置:首页 > 其它

strtok函数的妙用,分割字符串

2015-01-13 11:25 561 查看
strtok分割字符串函数,很好的解决了字符分割的要求,不必遍历取关键字再区后面字符

这样字符串中查找关键值获取后面的东西就方便多了

#include <string.h>

//加啊如头文件

char * strtok ( char * str, const char * delimiters );


参数含义

str :: 第一次操作时原始字符串,当strtok分割一次成功后 ,设置为 NULL 继续扫描下面的字符 知道为空

delimiters  ::   标记字符  分割的中间值如 xiaowan#xiaoli 符号#


简单的例子如下

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");// 此处上面以成功一次 ,设置为空,继续扫描
}
return 0;
}

Edit
& Run

运行结果

Splitting string "- This, a sample string." into tokens:
This
a
sample
string


根据结果分析得出

字符串呗 ." ,-"这三个字符分割了

Return Value

If a token is found, a pointer to the beginning of the token.

Otherwise, a null pointer.

A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: