summaryrefslogtreecommitdiff
path: root/rushs/tinyprintf/my_strstr/my_strstr.c
blob: 36ac43974471c10fbde68790abfdfc6ede866ddf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "my_strstr.h"

#include <stddef.h>

int my_strstr(const char *haystack, const char *needle)
{
    if (needle == NULL || *needle == '\0')
    {
        return 0;
    }

    for (int i = 0; haystack[i]; i++)
    {
        if (haystack[i] == needle[0])
        {
            int j;
            for (j = 0;
                 haystack[i + j] && needle[j] && needle[j] == haystack[i + j];
                 j++)
            {
                continue;
            }
            if (needle[j] == '\0')
            {
                return i;
            }
            if (haystack[i + j] == '\0')
            {
                return -1;
            }
        }
    }
    return -1;
}