Jun 23, 2009

Token a string on the basis if a given delimiter.

Token a string on the basis if a given delimiter.
e.g S is the base string and D is the delimiter (could be a sequence of any valid chars)
S = ["who is the man who saw the eagle today went the wrong way?"]
D = ["the"]
Result = ["who is ", " man who saw ", " eagle today went ", " wrong way?"]
bool foo(char* S, char* D, char** str_arr)
{
if(!S||!D||!str_arr)
return NULL;
int p1=p2=p3=idx=0;
while(S[p2])
{
if(S[p2]==D[p3])
{
p3++;p2++;
if(p3==3)
{
p3=0;p2=p2-3;
char* str_new=malloc(sizeof(char)*(p2-p1+1));
if(!str_new) return false;
memcpy(str[p1],str_new,p2-p1);
str_new[p2-p1+1]='\0';
str_arr[idx++]=str_new;
p1=p2+3;
p2=p1;
}
else
{p2++;p3=0;}
}
}
if(p1!=p2)
{
char* str_new=malloc(sizeof(char)*(p2-p1+1));
if(!str_new) return false;
memcpy(str[p1],str_new,p2-p1);
str_new[p2-p1+1]='\0';
str_arr[idx++]=str_new;
}
return true;
}

No comments:

Post a Comment