在编写程序是发现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: