Strstr Implementation in C

StrStr : Locate SubString in String
Returns a pointer to the first occurrence of a substring within another string.
Syntax ptr = strstr( s, subs );
const char *s : points to the string to be scanned.
const char *subs : points to the (sub)string to scan for.
char *ptr : points to the first occurrence of the substring in the given string. If the substring is not found, this will be a null pointer.


strstr(const char *in, const char *str){
   char c;
   size_t len;
   c = *str++;
   if (!c)
   return (char *) in;
   len = strlen(str);
   do {
      char sc;
      do {
         sc = *in++;
         if (!sc)
            return (char *) 0;
      } while (sc != c);
   } while (strncmp(in, str, len) != 0);
   return (char *) (in – 1);
}

Related posts:

  1. Strncpy Implementation in C
  2. Strcmp Implementation in C

Comments are closed.