在编写程序是发现string.h中的strtok有些和想象的不同
比如对字符串“|2|”以"|"切分时,原以为会返回,第一为空字符串,第二个为2 ,第三个为空字符串。但是当使用时发现,第一为2,二、三均为NULL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* split(const char *strToken,const char* strDelimit)
{
char *p;
char *pd;
static char *ps ;
if (strToken != NULL)
ps = strToken;
p = ps;
while (*ps != '\0 ')
{
pd = strDelimit;
while ( (*pd != '\0') && (*pd != *ps))
pd ++;
if (*pd == *ps)
{
*ps = NULL;
ps++;
return p;
}
else
ps++;
}
ps = NULL;
}
int main(int argc, char *argv[])
{
char str[10]="|2|";
char * first=strtok(str,"|");
char * second=strtok(NULL,"|");
char * third=strtok(NULL,"|");
printf("first:%s\n",first);
printf("second:%s\n",second);
printf("third:%s\n",third);
first=split(str,"|");
second=split(NULL,"|");
third=split(NULL,"|");
printf("first:%s\n",first);
printf("second:%s\n",second);
printf("third:%s\n",third);
system("PAUSE");
return 0;
}
打印结果
first:2
second:<NULL>
third:<NULL>
first:
second:2
thirsd:
本文深入探讨了C语言中string.h库中strtok函数在处理字符串分隔时的行为差异,通过实例展示了如何正确使用strtok函数进行字符串切分。
1004

被折叠的 条评论
为什么被折叠?



