ft_strtrim - chanhl22/libft GitHub Wiki
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ft_strtrim.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: chanhlee <[email protected].> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2021/01/28 21:33:51 by chanhlee #+# #+# */
9 /* Updated: 2021/01/28 21:40:39 by chanhlee ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12
13 #include "libft.h"
14
15 char *ft_strtrim(char const *s1, char const *set)
16 {
17 size_t begin; //๋ฌธ์๋ฅผ ์ ๊ฑฐํ๊ธฐ ์ํด์ ์์ ํฌ์ธํธ์ ๋ ํฌ์ธํธ๋ฅผ ์ก๋๋ค
18 size_t end;
19 char *result;
20 int i;
21
22 if (!s1)
23 return (NULL);
24 if (!set)
25 return (ft_strdup(s1)); //๋ฐํํ๋ฉด ๊ทธ๋๋ก ๋์์ผํจ
26 begin = 0;
27 while (s1[begin] != '\0' && ft_strchr(set, s1[begin])) //๋ฌธ์์ด ๋ด์ ์ผ์นํ๋ ๋ฌธ์๊ฐ ์๋์ง ๊ฒ์ฌ (์กด์ฌํ์ง ์์ผ๋ฉด NULL๋ฐํ)
28 begin++;
29 end = ft_strlen(s1);
30 while (end > start && ft_strchr(set, s1[end - 1])) //์ธ๋ฑ์ค๋ฅผ ์ฐพ์๋ 0๋ถํฐ ์์ํ๋ 1์ ๋นผ์ผํจ, ๋ฌธ์ ์ผ์น ๊ฒ์ฌ
31 {
32 end--;
33 }
34 if (!(result = (char*)malloc(sizeof(char) * (end - begin + 1)))) //ํ ๋น์ ํด์ค
35 return (NULL);
36 i = 0;
37 while (begin < end) //end๊ฐ ๋ ํด๋ ๋ฌธ์๋ฅผ ๋ณต์ฌํด์ผํ๋ค.
38 result[i++] = s1[start++];
39 result[i] = '\0';
40 return (result);
41 }