Header Ads

How to implement your own strstr function in C without using any library function

#include <stdio.h>

char *strstr(const char *haystack, const char *needle)

{

               char *retval = NULL;

               int needlelen = sizeof(needle);

               int haystacklen = sizeof(haystack);

               int lp1 = 0u;

               int lp2 = 0u;

               int firstMatchFlag = 0u;

               int fullMatchFlag = 0u;  

 

               if(haystack !=  NULL && needle != NULL)

               {

                              for(lp2 = 0; lp2 <= haystacklen; lp2++)

                              {

                                             if(firstMatchFlag == 0u)

                                             {

                                                            if(*(needle + lp1) == *(haystack + lp2))

                                                            {

                                                                           lp1 = lp1 + 1u;   

                                                                           firstMatchFlag = 1u;

                                                            }             

                                             }

                                             else

                                             {

                                                            if(lp1 == needlelen)

                                                            {

                                                                           fullMatchFlag = 1u;

                                                                           retval = (haystack + lp2 - needlelen);

                                                            }                                           

 

                                                            if(*(needle + lp1) == *(haystack + lp2))

                                                            {

                                                                           lp1 = lp1 + 1u;                                                

                                                            }

                                                            else

                                                            {

                                                                           firstMatchFlag = 0u;

                                                            }                                           

                                             }

                              }

               }

               return retval;

}

 

int main(void)

{   

    char *ptr =  strstr("My name is Kapil", "name");  

    if(ptr != NULL)

    {

        printf("%s", ptr);

    }

 

               return 0;

}