aboutsummaryrefslogtreecommitdiff
path: root/c09/ex02/ft_split.c
blob: e1c0186f645e3a0e523121287239eff18f57bc86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <charles.cabergs@gmail.com>       +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/07/08 15:58:03 by cacharle          #+#    #+#             */
/*   Updated: 2019/07/15 09:21:14 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <stdlib.h>

int		in_charset(char character, char *charset)
{
	while (*charset)
		if (character == *charset++)
			return (1);
	return (0);
}

int		count_segment(char *str, char *charset)
{
	int	counter;

	counter = 0;
	while (*str)
	{
		if (!in_charset(*str, charset))
		{
			counter++;
			while (!in_charset(*str, charset) && *str)
				str++;
			if (!*str)
				break ;
		}
		str++;
	}
	return (counter);
}

char	**heck(char *str, char *charset, char *tmp, int i)
{
	char	**strs;
	int		j;

	if ((strs = (char**)malloc(sizeof(char*)
			* (count_segment(str, charset) + 1))) == NULL)
		return (NULL);
	j = 0;
	while (*str)
	{
		while (in_charset(*str, charset))
			str++;
		i = 0;
		while (!in_charset(str[i], charset) && str[i])
			i++;
		if ((tmp = (char*)malloc(sizeof(char) * i + 1)) == NULL)
			return (NULL);
		i = 0;
		while (!in_charset(*str, charset) && *str)
			tmp[i++] = *str++;
		tmp[i] = '\0';
		strs[j++] = tmp;
	}
	strs[j] = 0;
	return (strs);
}

char	**ft_split(char *str, char *charset)
{
	if (!*str)
		return (NULL);
	return (heck(str, charset, NULL, 0));
}