Domanda di colloquio di Microsoft

implement strtok

Risposte di colloquio

Anonimo

19 ott 2014

char * my_strtok(char * str, char *token) { static char *buffer; if(str != NULL) buffer = str; if(buffer == NULL) return NULL; char * res = buffer; char *b, *d; for (b = buffer; *b!= '\0'; b++) { for (b= token; *d != '\0'; d++){ if(*b==*d){ *b = '\0' b = b+1; // skip if the match is the start if(res == b){ res++; continue; } return res; } } } return res; }

10

Anonimo

20 nov 2014

Here is a more elegant and easier to understand solution in my opinion. char * strtoken(char * string, char * delim) { static char * lastToken = NULL; /* Set string to the last saved state when the user passes NULL */ if(string == NULL) string = lastToken; /* We done boys, pack your bags. */ if(lastToken == NULL) return NULL; /* Find every character in delim and replace every instance of those in string with a \0 */ for(int i = 0; i < strlen(string); i++) { for(int j = 0; j < strlen(delim); j++) { if(string[i] == delim[j]) { string[i] = '\0'; } } } /* Increment our save pointer with the length of the last string */ lastToken += strlen(string); return string; }

2

Anonimo

20 nov 2014

Fixed a few bugs from before: char * strtoken(char * string, char * delim) { static char * lastToken = NULL; /* Set string to the last saved state when the user passes NULL */ if(string == NULL) string = lastToken; /* We done boys, pack your bags. */ if(string == NULL) return NULL; /* Find every character in delim and replace every instance of those in string with a \0 */ for(int i = 0; i < strlen(string); i++) { for(int j = 0; j < strlen(delim); j++) { if(string[i] == delim[j]) { string[i] = '\0'; /* Remove extra delimeters*/ if(!strcmp(string,"")) string = strtoken(string + 1, delim); /* Increment our save pointer starting at the index after the \0 */ lastToken = strchr(string, '\0') + 1; return string; } } } /* No more tokens, let's get out of here */ lastToken = NULL; if(!strcmp(string,"")) return NULL; return string; }

1

Anonimo

20 apr 2015

one are more if condition is used. first condition is string (str) then second condition is buffer is not correct.