ft_strncmp.c - chanhl22/libft GitHub Wiki
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ft_strncmp.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: chanhlee <[email protected].> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2021/01/20 11:49:50 by chanhlee #+# #+# */
9 /* Updated: 2021/02/01 23:11:49 by chanhlee ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12
13 #include "libft.h"
14
15 int ft_strncmp(const char *s1, const char *s2, size_t n)
16 {
17 unsigned char *ptr_s1;
18 unsigned char *ptr_s2;
19 size_t i;
20
21 ptr_s1 = (unsigned char *)s1;
22 ptr_s2 = (unsigned char *)s2;
23 i = 0;
24 while (s1[i] != '\0' && s2[i] != '\0' && i < n && ptr_s1[i] == ptr_s2[i]) // s1๊ณผ s2๊ฐ null์ด ์๋๋, n์ผ๋ก ์นด์ดํธ๋ฅผ ํด์ผํ๋ฏ๋ก 0~n-1๊น์ง ์ฐพ์์ผํ๋ค. ๊ทธ๋ฆฌ๊ณ str2๊ฐ์ ๋ฌธ์๊ฐ ๊ฐ๋ค๋ฉด
25 {
26 i++;
27 }
28 if (i == n) //i = n์ด๋ผ๋ฉด ํจ์์ ๋ฐํ๊ฐ์ธ 0์ ๋ฆฌํด (๋น๊ตํ ๊ฐ์ด ๋์ผํ๋ฉด 0๋ฐํ)
29 return (0);
30 return (ptr_s1[i] - ptr_s2[i]); //๊ฐ์ง ์๋ค๋ฉด 0์ด ์๋ ๋ฐํ๊ฐ ๋ฆฌํด
31 }