Monday, May 24, 2010

Can you write a "split" function in C?

I blew an interview because I screwed up my pointer arithmetic while parsing a string:





Here is the syntax:





prompt%26gt;./split "This Is an input string" " "





output:


This


is


an


input


string





or:


prompt%26gt;./split "This is an input string" "p"


output:


this is an in


ut string





I tried putting '\0' wherever the split character occurred, but I couldn't turn it into an array of substrings.





Any ideas?

Can you write a "split" function in C?
Only strlen, strcpy, and strcat, eh? That's pretty harsh. I think you have the right idea putting '\0' at the split points. Instead of creating an array of substrings, though, create an array of pointers to the substrings.





Pseudocode:





char *s points to your input string


S is an array of pointers to char


char *p declared to walk through the input string


initialize p = s, i = 0





do {


set S[i++] = p


set p to next split point


set *p = '\0'


p = p + 1


} until last substring found





How about that? You don't even need any of those string.h functions!
Reply:And you weren't allowed to use strtok?


No comments:

Post a Comment