Monday, September 22, 2008

Search a Substring in String(Special

This is a program that i make for searching a substring in string using three variable
1 haystack :The main String
2 needle     :The substring
3 offset       : The starting position of the main string from where substring start search
                        If you set it then it work from specified position other wise it works from 0. 

/*If you have function using less than three variable without using standard function in this stripos function then send me.*/

#include
#include
int stripos(char *haystack,char * needle,int offset)
{
//--------------------------If condition for start the string from given offset-------------------------------------
if(offset>0)
{
haystack=haystack+(offset-1);
}
else
{
offset=1;
}
//------------------------This while loop for check the condition untill the string has characters------
while((*haystack)!='\0')
{
if((*needle)=='\0')   /* This if condition for check for the end of the needle */
{
return offset; 
}
if((*haystack)==(*needle))    /* This condition for matching the character of haystack and needle */
{
if(stripos(haystack+1,needle+1,0)!=-1)    /* This is recursion for checking that all char of needle matched with this*/
{
return offset;
}
else
    break;
}
else
{
if((*(needle-1))!='\0')              /*This condition for returning in the recursion  if */
{
if(*haystack!=*needle)
{
return -1;
}
}
}
haystack++;
offset++;
}

return -1;
}
int main()
{
int pos=0;
pos=stripos("sandeepSinghbisht","Singh",0);
printf("%d",pos);
return 0;
}

No comments: