Amazon Interview Question
Software Engineer / Developers/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
Output:
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
Here is a sample code:
{static char *ts = NIL; /* string to locate tokens */
char *strtok (char *s,char *ct)
{
char *t;
if (!s) s = ts; /* use previous token if none specified */
if (!(s && *s)) return NIL; /* no tokens */
/* find any leading delimiters */
do for (t = ct, ts = NIL; *t; t++) if (*t == *s) {
if (*(ts = ++s)) break; /* yes, restart seach if more in string */
return ts = NIL; /* else no more tokens */
} while (ts); /* continue until no more leading delimiters */
/* can we find a new delimiter? */
for (ts = s; *ts; ts++) for (t = ct; *t; t++) if (*t == *ts) {
*ts++ = '\0'; /* yes, tie off token at that point */
return s; /* return our token */
}
ts = NIL; /* no more tokens */
return s; /* return final token */
}}
Does this mean deleting every instance of a particular substring from the source string?
- Ravi August 26, 2006