ft_split - chanhl22/libft GitHub Wiki
13 #include "libft.h"
14
15 int number_of_word(char const *s, char c)
16 {
17 int i;
18 int count;
19
20 i = 0;
21 count = 0;
22 while (s[i] != '\0')
23 {
24 if (s[i] == c)
25 i++;
26 else
27 {
28 count++;
29 while (s[i] && s[i] != c)
30 i++;
31 }
32 }
33 return (count);
34 }
35
36 char *make_word(char *res, char const *s, int j, int word_len)
37 {
38 int i;
39
40 i = 0;
41 while (word_len > 0) //์ค์ ๋ก ์ชผ๊ฐ ๋จ์ด๋ค์ ๋ณต์ฌํ๋ค.
42 {
43 res[i] = s[j - word_len];
44 i++;
45 word_len--;
46 }
47 res[i] = '\0';
48 return (res);
49 }
50
51 char **ft_split2(char **word, char const *s, char c, int num)
52 {
53 int i;
54 int j;
55 int word_len;
56
57 i = 0;
58 j = 0;
59 word_len = 0;
60 while (s[j] && i < num) //์ฌ๊ธฐ์ num์ ๋จ์ด์ ๊ฐ์์ด๋ค. ๋จ์ด์ ๊ฐ์๋ณด๋ค ์๊ฒ ๋ฐ๋ณตํ๋ค.
61 {
62 while (s[j] && s[j] == c) //j๋ s๋ฌธ์์ด์์ ์ธ๋ฑ์ค์ด๋ค. ๊ฐ๊ฑฐ๋ ๊ฐ์ง ์์๋ ๋ฌด์กฐ๊ฑด 1์ฉ ์ฆ๊ฐํด์ผํ๋ค.
63 j++;
64 while (s[j] && s[j] != c) //๊ฐ์ง ์์๋
65 {
66 j++;
67 word_len++; // ์ฐ๋ฆฌ๊ฐ ๋ฃ์ด์ผํ๋ ๋จ์ด๊ธธ์ด๋ฅผ ๊ฐ์ด ์ฆ๊ฐ์ํจ๋ค.
68 }
69 if (!(word[i] = (char *)malloc(sizeof(char) * (word_len + 1)))) //์ค์ ๋ก ํฌ์ธํฐ์ ๋ด์์ฃผ์ด์ผํ๊ธฐ ๋๋ฌธ์ ๋ ํ ๋น
70 return (NULL);
71 make_word(word[i], s, j, word_len); ์ค์ ๋ก ์ชผ๊ฐ ๋จ์ด๋ฅผ ํฌ์ธํฐ์ ์ ์ฅํ๋ ํจ์
72 word_len = 0; //๋ค์ ์ชผ๊ฐ 2๋ฒ์งธ ๋จ์ด๋ฅผ ์ํด 0์ผ๋ก ์ด๊ธฐํ
73 i++;
74 }
75 word[i] = NULL; //๋ง์ง๋ง์ NULL, ์ฌ๊ธฐ์ ์ด์คํฌ์ธํฐ๋ผ์ '\0'์ ๋ชป์ด๋ค. (์๋ฌ๊ฐ ๋๋๋ผ)
76 return (word);
77 }
78
79 char **ft_split(char const *s, char c)
80 {
81 char **word;
82 int num;
83
84 if (s == NULL) // ์ฐ์ s๊ฐ NULL์ผ๋ NULL์ ๋ฆฌํดํจ
85 return (NULL);
86 num = number_of_word(s,c); //number_of_wordํจ์๋ ๋ค์ด์จ ๋ฌธ์์ด์ด ๊ตฌ๋ถ ๋ฌธ์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ช๊ฐ๋ก ๋๋ ์ง์ง ๊ฐฏ์๋ฅผ ์ธ๋ ํจ์ ์ด๋ค. ์ฌ๊ธฐ์ ๋ง์ฝ์ c๊ฐ NULL์ด๋ผ๋ฉด count๊ฐ 1์ด ๋์ด์ผ s๊ฐ ๊ทธ๋๋ก ๋์จ๋ค.
87 if (!(word = (char**)malloc(sizeof(char*) * (num + 1)))) //์ด์ ์ชผ๊ฐ ๋จ์ด๋ฅผ ์ด์คํฌ์ธํฐ์ ์ ์ฅํด์ผํ๋ค. ๊ทธ๋์ ๋์ ํ ๋น์ ํด์ค๋ค.
88 return (NULL); //
89 ft_split2(word, s, c, num); // ์ชผ๊ฐ ๋จ์ด๋ฅผ ์ด์คํฌ์ธํฐ์ ์ ์ฅํ๊ธฐ ์ํด ์ค์ ๋ก ๋ฌธ์์ด์ ์ชผ๊ฐ๋ ํจ์ ํธ์ถ
90 return (word);
91 }