Trying to build my own strstr() function in c?

161 views Asked by At

I'm trying to build my strstr() function, it's look all fine but when I execute the code it return nothing ;

This is my function :

#include <stdio.h>

char* ft_strstr(char *str, char *to_find) {
  char *a;
  char *b;

  b = to_find;
  if (!*b)
    return (char*) str;
  while (*str) {
    if (*str != *b)
      continue;
    a = str;
    while (1) {
      if (!*b)
        return (char*) str;
      if (*a++ != *b++)
        break;
    }
    str++;
    b = to_find;
  }
  return (NULL);
}

int main() {
  char string[] = "Hello from morroco";
  char find[] = "from";
  ft_strstr(string, find);
  printf("%s", find);
  return 0;
}

I don't know what. I have to try to fix it cause it looks all fine for me.

1

There are 1 answers

7
Vlad from Moscow On

There is a bug in this if statement

if(*str != *b)
    continue;

the pointer str is not increased in this case and as a result the loop will be infinite.

instead of the while loop it is better to use a for loop as

for ( ; *str; ++str )

or the while loop can look like

while (*str)
{
    if( *str == *b )
    {
        a = str;
        while(1)
        {
            if (!*b )
                return (char *)str;
            if (*a++ != *b++)
                break;
        }
    }
    str++;
    b = to_find;
}

Also it seems you mean

char *pos = ft_strstr(string , find);
if ( pos ) printf("%s", pos);

instead of

ft_strstr(string , find);
printf("%s", find);

Pay attention to that the function should be declared like

char * ft_strstr( const char *str, const char *to_find);

And using such castings like

return (char *)str;

makes sense if the parameter str has the type const char * as it should have.