char **ft_split(char const *s, char c)
char *make_word(const char *s, int n): 문자열 s에서 n만큼 글자를 복사해 새 문자을 만드는 함수이다. 즉, 한 단어를 만들기 위해 사용되는 함수이다.
char **free_all(char **list): list 배열의 모든 요소들을 할당 해제하고 list도 할당 해제해주는 함수이다.
int word_count(char const *s, char c): 문자열 s를 순회하며 구분자 c가 아닌 부분을 찾아서 단어를 세는 함수이다.
#include "libft.h"
static char *make_word(const char *s, int n)
{
int i;
char *str;
i = 0;
str = NULL;
if (n == 0)
return (NULL);
str = (char *)malloc(sizeof(char) * (n + 1));
if (str == 0)
return (NULL);
while (i < n)
{
str[i] = s[i];
i++;
}
str[i] = '\0';
return (str);
}
static char **free_all(char **list)
{
int i;
i = 0;
while (list[i])
{
free(list[i]);
i++;
}
free(list);
return (NULL);
}
static int word_count(char const *s, char c)
{
int count;
int i;
i = 0;
count = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
count++;
while (s[i] && s[i] != c)
i++;
}
}
return (count);
}
char **ft_split(char const *s, char c)
{
char **result;
int i;
int k;
int save;
i = 0;
k = 0;
result = (char **)malloc(sizeof(char *) * (word_count(s, c) + 1));
if (!result)
return (NULL);
while (i < word_count(s, c) && s[k] != '\0')
{
while (s[k] == c)
k++;
save = k;
while (s[k] != c && s[k] != '\0')
k++;
result[i] = make_word(&s[save], k - save);
if (result[i++] == 0)
return (free_all(result));
}
result[i] = NULL;
return (result);
}
split 작동 순서
- word_count를 이용해 단어 개수를 구함
- malloc으로 단어 개수 + 1칸(=NULL 포인터용) 배열을 할당
- 문자열을 순회하면서구분자를 건너뛰고 단어의 시작 위치를 기억
- 단어 끝까지 이동 후 make_word로 단어를 할당 (실패 시 free_all 호출)
- 마지막에 배열 끝에 NULL 저장
- 완성된 이중 포인터 배열 반환
int main(void)
{
char *s;
char **result;
int i;
s = "Hello world 42 Gyengsan";
result = ft_split(s, ' ');
printf("Test 1: \"%s\"\n", s);
for (i = 0; result[i]; i++)
printf("Word %d: %s\n", i, result[i]);
for (i = 0; result[i]; i++)
free(result[i]);
free(result);
return 0;