#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
char *str1, *str2, *token, *subtoken;
char *saveptr1 = NULL, *saveptr2 = NULL;
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) {
printf("saveptr1 = %s \n",saveptr1);
token = strtok_r(str1, argv[2], &saveptr1);
printf("str1 = %s, argv[2] = %s, saveptr1 = %s \n",str1, argv[2], saveptr1);
printf("token = %s \n",token);
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);
}
Execute code :./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'
saveptr1 = (null)
str1 = a/bbb///cc, argv[2] = :;, saveptr1 = xxx:yyy:
token = a/bbb///cc
1: a/bbb///cc
--> a
--> bbb
--> cc
saveptr1 = xxx:yyy:
str1 = (null), argv[2] = :;, saveptr1 = yyy:
token = xxx
2: xxx
--> xxx
saveptr1 = yyy:
str1 = (null), argv[2] = :;, saveptr1 =
token = yyy
3: yyy
--> yyy
saveptr1 =
str1 = (null), argv[2] = :;, saveptr1 =
token = (null)
Reference: strtok_r(3) - Linux man page
0 意見:
張貼留言