Interview Questions

Implement the tokenize function in C and how do you handle multiple spaces between words ?........

Microsoft Interview Questions and Answers


(Continued from previous question...)

121. Implement the tokenize function in C and how do you handle multiple spaces between words ?........

Question:
Implement the tokenize function in C and how do you handle multiple spaces between words ?
So if the string is "abc def (2spaces)ghi" how do you separate out words in an array ?


maybe an answer:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/* * tokenize() is based on strsep()
* The only difference is how they handle the empty fields.
*/

bool match(char *c, const char *delim)
{
unsigned int len = strlen(delim);
for (unsigned int i = 0; i < len; i++) {
if (*c == *(delim + i))
return true;
}
return false;
}
char *tokenize(char **stringp, const char *delim)
{
char *p = *stringp;
// If *stringp is initially NULL, strsep() returns NULL.
if (*stringp == NULL)
return NULL;
unsigned int len = strlen(*stringp);
for (unsigned int i = 0; i < len; i++) {
/*
* locates, in the string referenced by *stringp, the
* first occurrence of any character in the string delim
* and replaces it with a '\0'
*/
if (match(p + i, delim)) {
*(p + i) = '\0';
for (unsigned int j = 1; j < len - i - 1; j++) {
/*
* The location of the next non-delimiter character after
* the delimiter character (or NULL, if the end of the
* string was reached) is stored in *stringp.
*/
if (!match(p + i + j, delim)) {
*stringp = (p + i + j);
break;
}
}
break;
}
}
if (*stringp == p)
*stringp = NULL;
// The original value of *stringp is returned.
return p;
}
int main()
{
char *token, *string, *tofree;
tofree = string = strdup("abc def ,ghi");
assert(string != NULL);
while ((token = tokenize(&string, " ,")) != NULL) {
printf("%s\n", token);
}
free(tofree)
}

(Continued on next question...)

Other Interview Questions