ft_split

nawkim·2021년 5월 26일
0

libft

목록 보기
28/44

1. 프로토타입

char	**ft_split(char const *s, char c)

2. 용도

3. 리턴값

4. 코드 구현

#include "libft.h"

static void	ft_malloc_free(char **ret, int k)
{
	int		t;

	t = 0;
	while (t < k)
	{
		free(ret[t]);
		t++;
	}
	free(ret);
}

static char	*ft_put_split(int size, char const *s)
{
	int		t;
	char	*p;

	t = 0;
	p = (char *)malloc(sizeof(char) * (size + 1));
	if (p == 0)
	{
		return (NULL);
	}
	while (t < size)
	{
		p[t] = s[t];
		t++;
	}
	p[t] = '\0';
	return (p);
}

static int	ft_find_start(char const *s, char c, int end)
{
	int		t;

	t = end;
	if (t == 0 && s[t] != c)
		return (0);
	while (s[t] != '\0')
	{
		if (s[t] == c && s[t + 1] != c)
			return (t + 1);
		t++;
	}
	return (t);
}

static char	**ft_check_start_split(char const *s, char c, char **ret, int k)
{
	int		t;
	int		start;
	int		end;

	end = 0;
	t = -1;
	while (s[++t] != '\0')
	{
		start = ft_find_start(s, c, end);
		if (t >= start && (s[t] != c && (s[t + 1] == c || s[t + 1] == '\0')))
		{
			end = t + 1;
			if (end - start > 0)
			{
				if ((ret[++k] = ft_put_split(end - start, s + start)) == NULL)
				{
					ft_malloc_free(ret, k);
					return (0);
				}
			}
		}
	}
	ret[++k] = 0;
	return (ret);
}

char		**ft_split(char const *s, char c)
{
	int		cnt;
	int		t;
	char	**ret;

	t = 1;
	cnt = 0;
	if (s[0] != c)
		cnt++;
	if (s[0] != '\0')
	{
		while (s[t] != '\0')
		{
			if (s[t - 1] == c && s[t] != c)
				cnt++;
			t++;
		}
	}
	ret = (char **)malloc(sizeof(char*) * (cnt + 1));
	if (ret == 0)
		return (0);
	ret = ft_check_start_split(s, c, ret, -1);
	return (ret);
}

5. 코드 설명

profile
공부 기록.

0개의 댓글