#include <string.h> #include <stdio.h> int main(void) { char input[16] = "abc,d"; char *p; /**//* strtok places a NULL terminator in front of the token, if found */ p = strtok(input, ","); if (p) printf("%s\n", p); /**//* A second 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; } [解决办法]
[解决办法] 原型 char *strtok(char *s, const char *delim); 功能 分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。 说明 strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。 返回值 从s开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。 所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。 strtok函数在C和C++语言中的使用 strtok函数会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。如果 要保持原字符串的完整,可以使用strchr和sscanf的组合等。 c #include <string.h> #include <stdio.h> int main(void) { char input[16] = "abc,d"; char *p; /**/ /* strtok places a NULL terminator in front of the token, if found */ p = strtok(input, ","); if (p) printf("%s\n", p); /**/ /* A second 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; }