strtok, strtok_r - extract tokens from strings
//从字符串中提取标记
#include <string.h>
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int j;
if (argc != 4) {
fprintf(stderr, "Usage: %s string delim subdelim\n",
argv[0]);
exit(EXIT_FAILURE);
}
for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
token = strtok_r(str1, argv[2], &saveptr1);
if (token == NULL)
break;
printf("%d: %s\n", j, token);
for (str2 = token; ; str2 = NULL) {
subtoken = strtok_r(str2, argv[3], &saveptr2);
if (subtoken == NULL)
break;
printf(" --> %s\n", subtoken);
}
}
exit(EXIT_SUCCESS);
}
编译输出可执行文件a.out,输入指令
./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'
#include <string.h>
#include <stdio.h>
int main(void)
{
char input[16] = "abc,d,D,E";
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);
//p = strtok(NULL, ",");
//if (p) printf("%s\n", p);
//p = strtok(NULL, ",");
//if (p) printf("%s\n", p);
while(p = strtok(NULL, ","))
{
printf("%s\n", p);
}
return 0;
}
测试结果: