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 }