Code Infinity

SAVE THE EARTH.............

Sunday, September 14, 2008

code snippet for finding position of any sub-string in a main-string.

Hey guys, here i am with a small but sometimes useful code. This code snippet will find the position of any sub-string in the main-string. So, here we goooooo...........

int find_pos(char *main,char *sub)
{

int count=0;    //initiallizes count with zero.
int len=strlen(sub); //calculates the length of sub-string
int pos=0;  //initiallizes pos with zero.

for(int i=0;main[i]!='\0';i++)
{   //loop to analyse the characters of  main string.

if(sub[0]==main[i])
{   // if the first character of sub matches with the charater of main,THEN
for(int j=0;sub[j]!='\0';j++)
{  //checks the preceeding character of sub & main.
if(sub[j]==main[i+j])
{
count++;   // if TRUE, the adds 1 to count.
if(count==len) //if count is equal to len, THEN saves the values of
{ // 'i' in 'pos'.As this the location of sub-string.
  pos=i;
break;  //After saving, break the loop.
}
}
}
}

if(count==len) //if count is equal to len then break the main loop.
break;
}

return pos; // return position of sub-string.

}

Is it scaring? But i don't thing so. It is a very simple and properly documented program. If you require any help regarding programming in c++ and assembly language you can mail me. I will try to sort you out. 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home