Apr 19, 2011

Find Substring in a given String

int findsubstr(char* src, char* trg, int srclen, int trglen)
{
if((srclen < trglen) (srclen < 1) (trglen < 1) (!src) (!trg))
return -1;

for(int i=0; i < srclen-trglen+1; i++)
{
//now compare the src with trg
int j=0;
for(; j < trglen; j++)
{
if(src[i+j] != trg[j])
break; //not found, restart with next src character
}
if(j==trglen)
return i;
}

return -1;
}

1 comment:

Swetank said...

Another similar method:

char* mystrstr(char *s2, char *s1)
{
if(!s1 && !s2)
return NULL;

char* t = s1;
int len = 0;

while(*s2)
{
if(*s2 != *s1)
{
s1=t; //reset to start
len = 0;
}
else
{
s1++; //inc to match next
len++;
}

if(!*s1)
return s2-len-1; //match found return current pointer of s2

s2++;
}