Skip to content

Instantly share code, notes, and snippets.

@ayaderaghul
Last active April 20, 2018 09:00
Show Gist options
  • Save ayaderaghul/b90d37b7d23da688fbd345aaedc3df98 to your computer and use it in GitHub Desktop.
Save ayaderaghul/b90d37b7d23da688fbd345aaedc3df98 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *ft_strnstr(const char *haystack, const char *needle, size_t len)
{
size_t i;
size_t j;
if (needle[0] == '\0')
return ((char *)haystack);
j = 0;
while (j < len && haystack[j])
{
i = 0;
while (needle[i] && haystack[j] && needle[i] == haystack[j])
{
++i;
++j;
}
if (needle[i] == '\0')
return ((char *)&haystack[j - i]);
j = j - i + 1;
}
return (0);
}
int main()
{
char *s1 = "MZIRIBMZIRIBMZE123";
char *s2 = "MZIRIBMZE";
size_t max = strlen(s2);
char *i1 = strnstr(s1, s2, max);
char *i2 = ft_strnstr(s1, s2, max);
printf("strnstr: %s\nft_strnstr: %s\n", i1,i2);
return 0;
}
@pgiammel
Copy link

try this

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

char    *ft_strnstr(const char *haystack, const char *needle, size_t len)
{
    size_t  i;
    size_t  j;

    if (needle[0] == '\0')
        return ((char *)haystack);
    j = 0;
    while (j < len && haystack[j])
    {
        i = 0;
        while (j < len && needle[i] && haystack[j] && needle[i] == haystack[j])
        {
            ++i;
            ++j;
        }
        if (needle[i] == '\0')
            return ((char *)&haystack[j - i]);
        j = j - i + 1;
    }
    return (0);
}

int main()
{

    char    *s1 = "MZIRIBMZIRIBMZE123";
    char    *s2 = "MZIRIBMZE";
    size_t  max = strlen(s2);

    char    *i1 = strnstr(s1, s2, max);
    char    *i2 = ft_strnstr(s1, s2, max);


    printf("strnstr: %s\nft_strnstr: %s\n", i1,i2);
    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment