split 뭐예여
문자열을 주어진 구분자 기준으로 잘라서 문자열 배열로 만들어주는 함수
함수 원형: char ft_split(char const s, char c)**
**char const s: 원본 문자열
char c:** 원본 문자열을 잘라낼 구분자 문자열
#include "libft.h"
static size_t ft_word_count(const char *s, char c) //단어의 개수를 세는 함수
{
size_t count;
count = 0;
while (*s)
{
while (*s == c && *s) //구분자 스킵
s++;
if (*s) //단어가 시작되면
{
count++; //단어 하나 카운트
while (*s && *s != c) //단어 끝까지 이동
s++;
}
}
return (count);
}
static char *ft_word_dup(const char *start, size_t len) //start 포인터에서 len만큼 복사해서 새로운 단어를 만드는 함수
{
char *word;
size_t i;
i = 0;
word = (char *)malloc(len + 1); // +1은 널문자 공간
if (!word)
return (NULL);
while (i < len) //단어 복사
{
word[i] = start[i];
i++;
}
word[i] = '\0'; //널 종료
return (word);
}
static char **ft_free(char **arr, size_t i) //실패했을때 지금까지 할당한 문자열을 전부 free해주는 함수
{
while (i--)
free(arr[i]); //하나씩 free
free(arr); //전체 배열도 free
}
static char **ft_split_word(char **arr, char const *s, char c) //문자열을 단어별로 잘라서 배열에 저장하는 함수
{
const char *start;
size_t len;
size_t i;
i = 0;
while (*s)
{
while (*s == c && *s) //구분자는 넘김
s++;
if (*s)
{
start = s; //단어 시작 저장
while (*s && *s != c) //단어 끝까지 이동
s++;
len = s - start; //단어 길이 계산
arr[i] = ft_word_dup(start, len); //단어 복사
if (!arr[i++]) //복사 실패시 메모리 정리
{
ft_free(arr, i);
return (NULL);
}
}
}
arr[i] = NULL; //배열 마지막에 NULL 추가
return (arr);
}
char **ft_split(char const *s, char c) //메인 함수
{
char **arr;
size_t count;
if (!s)
return (NULL);
count = ft_word_count(s, c); //단어 개수 세기
arr = (char **)malloc(sizeof(char *) * (count + 1)); //단어 수 + 널 공간
if (!arr)
return (NULL);
return (ft_split_word(arr, s, c)); //단어 분리 후 배열 리턴
}