Jul 2, 2016

C Programming #79: strstr implementation

C Programming #79: strstr implementation

Following article implements our own version of strstr implementation. Please review article strings and string.h library if not already done. Since our implementation function name would clash with standard implementation, lets prefix my_ to it. We know the prototype of my_strstr is as follow.

/*Find the first occurrence of the  sub-string  
needle  in  the  string  haystack, returning a 
pointer to the found sub-string. */
char *my_strstr(const char *haystack, const char *needle);

For this implementation we need to traverse haystack and do strncmp(variation of strcmp, which limits to n characters) with needle at different starting location of haystack. We could transform the above sentence into program as follows.

#include <stdio.h>
#include <string.h>
char *my_strstr(const char *haystack, const char *needle);
int main()
{
  printf("%s\n", my_strstr("Hello World", "Wo"));
  return 0;
}
char *my_strstr(const char *haystack, const char *needle)
{
  int i = 0;
  for(i = 0; i < strlen(haystack) - strlen(needle); i++) {
    if(strncmp(&haystack[i], needle, strlen(needle) - 1) == 0) {
      return (char*)haystack + i;
    }
  }
  return NULL;
}
World

Hope that clarifies the implementation. Never use custom implementation like this, always use the standard implementation provided in glibc.

No comments :

Post a Comment