ft_split: 문자열을 특정 문자 기준으로 쪼개서 이중 포인터에 저장하여 반환해주는 함수
ft_split("a12aaa12", 'a') = ["12", "12"]과 같은 방식으로 특정 문자가 덕지덕지 붙어있는 경우에도 잘 처리해야 한다.
1) 일단 이중 포인터를 할당해야 되기 때문에 문자열에서 분해되는 단어가 몇 개 일지를 미리 파악해야 한다.
이는 ft_word_count 함수에서 처리한다. 처리 방식은 아래 split 하는 방식과 거의 유사하다.
2) 문자열 맨 처음부터 들어있는 c들은 무시 즉 c가 아닌 다른 문자가 보일 때까지 문자열을 넘어가야 한다. 왜냐하면 앞에 쪼개서 저장할 문자가 없기 때문이다.
ex) ft_split("aaa11a", 'a') = ["11"] -> 보면 앞에 있는 a들은 아무 의미가 없다. '1'까지 넘어가 주면 된다.
3) c가 아닌 문자가 보였다면 그 위치부터 그다음에 있는 c의 위치 전까지의 문자들을 이중 포인터에 차례대로 저장해주면 된다.
그 후에 문자열 끝까지 2와 3을 반복해주면 된다.
ex) ft_split("aaa12aa345a", 'a') = ["12", "345"] -> 12, 345가 이중 포인터에 차례대로 저장된다.
쪼갠 단어를 이중 포인터에 저장하는 건 ft_word_make 함수, 실제로 문자열을 쪼개는 건 ft_split2 함수이다.
int ft_word_count(char const *s, char c)
{
int i;
int cnt;
i = 0;
cnt = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
cnt++;
while (s[i] && s[i] != c)
i++;
}
}
return (cnt);
}
char *ft_word_make(char *word, char const *s, int k, int word_len)
{
int i;
i = 0;
while (word_len > 0)
word[i++] = s[k - word_len--];
word[i] = '\0';
return (word);
}
char **ft_split2(char **result, char const *s, char c, int word_num)
{
int i;
int k;
int word_len;
i = 0;
k = 0;
word_len = 0;
while (s[k] && i < word_num)
{
while (s[k] && s[k] == c)
k++;
while (s[k] && s[k] != c)
{
k++;
word_len++;
}
if (!(result[i] = (char *)malloc(sizeof(char) * (word_len + 1))))
return (NULL);
ft_word_make(result[i], s, k, word_len);
word_len = 0;
i++;
}
result[i] = 0;
return (result);
}
char **ft_split(char const *s, char c)
{
int word_num;
char **result;
if (s == 0)
return (NULL);
word_num = ft_word_count(s, c);
if (!(result = (char **)malloc(sizeof(char *) * (word_num + 1))))
return (NULL);
ft_split2(result, s, c, word_num);
return (result);
}
kimjinho1/Libft
42 Seoul Libft. Contribute to kimjinho1/Libft development by creating an account on GitHub.
github.com
'42 SEOUL > Libft' 카테고리의 다른 글
42 서울 Libft(ft_putchar_fd, ft_putstr_fd, ft_putendl_fd, ft_putnbr_fd) (0) | 2021.01.25 |
---|---|
42 서울 Libft(ft_memcpy, ft_memccpy, ft_memchr, ft_memcmp, ft_memmove) (0) | 2021.01.24 |
42 서울 Libft(ft_atoi, ft_itoa) (0) | 2020.12.19 |
42 서울 Libft(ft_isalpha, ft_isdigit, ft_isalnum, ft_isascii, ft_isprint) (0) | 2020.12.19 |
42 서울 Libft(ft_bzero, ft_memset, ft_calloc) (0) | 2020.12.19 |