Comments: Flat Nested Threaded Embedded Oldest First Newest First Here is a c++ solution... By smalandren on Thursday, March 20, 2008 (UMST) I am new this site and this is my first post. I have found this website very interested, now just to prepare for an interview but also to have fun with some of the questions. My solution is below. It runs in O(2n), where n is the size of the input string. void StrTok(const char *str, char **&tokens, char delim){ char *strptr = (char *)str; char *ptrstart=strptr; int strlen=0; int ntokens=1; int tokendx=0; if( !str ) { tokens = NULL; return; } //Find # of tokens that will be created; while(*strptr) { if(*strptr == delim) { ntokens++; //Don't count consecutive delimeters while(*strptr++ == delim); continue; } strptr++; } //Now declarte the ntokens array of char* tokens = new char* [ntokens+1]; strptr = (char *)str; do { if(*strptr == delim || !(*strptr)) { strlen = strptr-ptrstart; *(tokens+ tokendx) = new char[strlen+1]; memcpy( *(tokens+ tokendx), ptrstart, strlen); (*(tokens+ tokendx++))[strlen]='\0'; ptrstart = strptr+1; //Don't count consecutive delimeters while(*strptr++ == delim); continue; } }while(*strptr++); *(tokens+ tokendx)=NULL;} I hope the code is clear enough Reply to this Comment Average Rating: well this is another question... By smalandren on Thursday, March 20, 2008 (UMST) Actually, I misread the question. I thought it was about writing a strtok funciton, but I think it is to rewrite the exisitng standard C one. Maybe if I have more time I will we write it. Reply to this Comment Average Rating:
I am new this site and this is my first post. I have found this website very interested, now just to prepare for an interview but also to have fun with some of the questions.
My solution is below. It runs in O(2n), where n is the size of the input string.
void StrTok(const char *str, char **&tokens, char delim){ char *strptr = (char *)str; char *ptrstart=strptr; int strlen=0; int ntokens=1; int tokendx=0; if( !str ) { tokens = NULL; return; } //Find # of tokens that will be created; while(*strptr) { if(*strptr == delim) { ntokens++; //Don't count consecutive delimeters while(*strptr++ == delim); continue; } strptr++; }
//Now declarte the ntokens array of char* tokens = new char* [ntokens+1]; strptr = (char *)str; do { if(*strptr == delim || !(*strptr)) { strlen = strptr-ptrstart; *(tokens+ tokendx) = new char[strlen+1]; memcpy( *(tokens+ tokendx), ptrstart, strlen); (*(tokens+ tokendx++))[strlen]='\0'; ptrstart = strptr+1;
//Don't count consecutive delimeters while(*strptr++ == delim); continue; } }while(*strptr++);
*(tokens+ tokendx)=NULL;}
I hope the code is clear enough
Reply to this Comment
Actually, I misread the question. I thought it was about writing a strtok funciton, but I think it is to rewrite the exisitng standard C one.
Maybe if I have more time I will we write it.