libft
Loading...
Searching...
No Matches
ft_strnstr.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_strnstr.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tspoof <tspoof@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2022/11/01 15:17:40 by tspoof #+# #+# */
9/* Updated: 2022/12/08 00:53:31 by tspoof ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "libft.h"
14
15// First checks if needles first char matches with a char in haystack.
16// Then compares needles and haystacks characters one by one
17// from that point froward.
18char *ft_strnstr(const char *haystack, const char *needle, size_t len)
19{
20 size_t i;
21 size_t j;
22 size_t needle_len;
23
24 if (*needle == '\0' || haystack == needle)
25 return ((char *)haystack);
26 if (len == 0)
27 return (NULL);
28 needle_len = ft_strlen(needle);
29 i = 0;
30 while (i < len && haystack[i])
31 {
32 if (haystack[i] == needle[0])
33 {
34 j = 0;
35 while (needle[j] && haystack[i + j] && haystack[i + j] == needle[j]
36 && i + j < len)
37 j++;
38 if (j == needle_len)
39 return ((char *)haystack + i);
40 }
41 i++;
42 }
43 return (NULL);
44}
char * ft_strnstr(const char *haystack, const char *needle, size_t len)
Search string from string.
Definition ft_strnstr.c:18
size_t ft_strlen(const char *s)
Length of the string.
Definition ft_strlen.c:15