C Interview Questions and Answers

 

How can I split up a string into whitespace-separated fields?

How can I split up a string into whitespace-separated fields? How can I duplicate
the process by which main() is handed argc and argv?





The only Standard function available for this kind of ``tokenizing'' is
strtok, although it can be tricky to use and it may not do everything you want it
to. (For instance, it does not handle quoting.) Here is a usage example, which simply
prints each field as it's extracted:



#include <stdio.h>



#include <string.h>



char string[] = "this is a test"; /* not char *;





char *p;



for(p = strtok(string, " tn"); p != NULL;



p = strtok(NULL, " tn"))



printf(""%s"n", p);





As an alternative, here is a routine I use for building an argv all at once:



#include <ctype.h>



int makeargv(char *string, char *argv[], int argvsize)



{



char *p = string;



int i;



int argc = 0;





for(i = 0; i < argvsize; i++) {



/* skip leading whitespace */



while(isspace(*p))



p++;





if(*p != '')



argv[argc++] = p;



else {



argv[argc] = 0;



break;



}





/* scan over arg */



while(*p != '' && !isspace(*p))



p++;



/* terminate arg: */



if(*p != '' && i < argvsize-1)



*p++ = '';



}





return argc;



}





Calling makeargv is straightforward:



char *av[10];



int i, ac = makeargv(string, av, 10);



for(i = 0; i < ac; i++)



printf(""%s"n", av[i]);

Posted by:Richards