Created
November 20, 2010 13:20
-
-
Save shihongzhi/707817 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
//strtok的实现和strtok_r一样,只是用一个static char*来维护saveptr | |
char *strtok_r(char *str,const char *delim,char **saveptr) | |
{ | |
char *ret; | |
if(str==NULL) | |
str=*saveptr; | |
while(*str && strchr(delim,*str)) | |
str++; | |
if(*str=='\0') | |
return NULL; | |
ret=str; | |
while(*str && !strchr(delim,*str)) | |
++str; | |
if(*str) | |
*str++='\0'; | |
*saveptr=str; | |
return ret; | |
} | |
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) { | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment