版权声明:共同提高:) https://blog.csdn.net/u011436427/article/details/82469697
参考的bolg:
strtokhttps://blog.csdn.net/huhaoxuan2010/article/details/76034310
strtok()函数详解!
https://blog.csdn.net/weibo1230123/article/details/80177898
1.头文件:
<cstring>或者<string.h>
2.声明:
char *strtok(char *str, const char *delimiters);
3.功能:
对该函数的连续调用,将会使一个完整字符串str以delimiters为分割符进行分割,最终得到一小片一小片各自独立的字符串。
4.如何使用:
在第一次调用时,该函数需要一个字符串参数str,它的第1个字符用来做扫描的起始位置。在随后的调用中,该函数需要一个null指针,并且使用最后一个字符的位置作为新的扫描起点。
5.参数:
str:要截取的字符串。
这个字符串将会被分割成更小的字符串。
还有另外一种可能,可能指定一个空指针,在这种情况下,该函数继续从前一个成功的调用开始扫描到该函数结束。
delimiters:包含分割字符。
从一个调用到另一个调用可能值会不同。
6.返回值:
1)从s开头开始的一个个被分割的串。当s中的字符查找到末尾时,返回NULL。如果查找不到delim中的字符时,返回当前strtok的字符串的指针(这个就是为啥下面这个函数p=strtok(NULL,",");这么写的原因了)。所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。
2)需要注意的是,使用该函数进行字符串分割时,会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。第一次分割之后,原字符串str是分割完成之后的第一个字符串,剩余的字符串存储在一个静态变量中,因此多线程同时访问该静态变量时,则会出现错误。
当到达字符串结尾时,总是会返回一个null指针。
#include<string.h>
#include<stdio.h>
int main(void)
{
char input[16]="abc,d";
char*p;
/*strtok places a NULL terminator
infront of the token,if found*/
p=strtok(input,",");
if(p)
printf("%s\n",p);
/*Asecond call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token*/
p=strtok(NULL,",");
if(p)
printf("%s\n",p);
return 0;
}
如果这么写的话,
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char input[16]="abc,d";
char*p;
/*strtok places a NULL terminator
infront of the token,if found*/
p=strtok(input,",");
if(p)
printf("%s\n",p);
/*Asecond call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token*/
/*
p=strtok(NULL,",");
if(p)
printf("%s\n",p);
*/
system("pause");
return 0;
}