/*--------------------------------------------------------------------*/ /* teststrtok.c */ /* Author: Xiaoyan Li */ /*--------------------------------------------------------------------*/ #include #include #include /*--------------------------------------------------------------------*/ /* Demonstrate strtok function. Return 0, or EXIT_FAILURE if wrong input. */ int main(int argc, char *argv[]) { char *str, *str_origin, *token; int i; if (argc != 3) { fprintf(stderr, "Usage: %s string delim \n", argv[0]); exit(EXIT_FAILURE); } if (*argv[1] == '\0'){ fprintf(stderr, "The string is an empty string!\n"); exit(EXIT_FAILURE); } /* Note: strtok() modifies the first argument. Therefore it cannot be used on constant strings. We do not want to change argv[1]. So we make a copy of it in the following code. strtok only returns non-empty strings. */ str = (char *)malloc(strlen(argv[1])+1); if (str == NULL){ fprintf(stderr, "There is no sufficient memory!\n"); exit(EXIT_FAILURE); } str_origin = str; /* points to the memory allocated by malloc!*/ /* 1. demonstrate strtok with a for loop!*/ printf("Using a for loop!\n"); strcpy(str, argv[1]); for (i = 1; ; i++, str = NULL) { token = strtok(str, argv[2]); if (token == NULL) break; printf("%d: %s\n", i, token); } /* 2. demonstrate strtok with a while loop!*/ printf("Using a while loop!\n"); str = str_origin; strcpy(str, argv[1]); i = 1; token = strtok(str, argv[2]); while(token!=NULL) { printf("%d: %s\n", i, token); i++; token = strtok(NULL, argv[2]); } free(str_origin); return 0; }