-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_strnstr.c
50 lines (45 loc) · 1.65 KB
/
ft_strnstr.c
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strnstr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcombeau <mcombeau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/25 23:07:33 by mcombeau #+# #+# */
/* Updated: 2021/12/03 16:33:24 by mcombeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION :
The function ft_strnstr searches the first n bytes of the given string
s1 for the first occurence of the full string s2.
Characters that appear after \0 are not searched.
RETURN VALUE :
A pointer to the first character of the first occurrence of s2.
A pointer to s1 if s2 is empty.
NULL if s2 occurs nowhere in s1.
*/
char *ft_strnstr(const char *s1, const char *s2, size_t n)
{
size_t s2len;
size_t i;
size_t j;
s2len = ft_strlen(s2);
if (s1 == s2 || s2len == 0)
return ((char *)s1);
i = 0;
while (i < n && s1[i] != '\0')
{
j = 0;
while (s1[i + j] != '\0' && s2[j] != '\0'
&& (i + j) < n && s1[i + j] == s2[j])
{
j++;
if ((j == n && j == s2len) || j == s2len)
return ((char *)(s1 + i));
}
i++;
}
return (0);
}