aboutsummaryrefslogtreecommitdiffstats
path: root/libft/src/ft_split.c
blob: 942377cc46c15be379ef75a4a95168d75c8f4f75 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: joelecle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:07:05 by joelecle          #+#    #+#             */
/*   Updated: 2020/02/14 17:07:05 by joelecle         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stddef.h>
#include <stdlib.h>
#include <inttypes.h>

static size_t
	ft_count_words(const char *s, char c)
{
	size_t	i;
	size_t	count;
	uint8_t	ibool;

	i = 0;
	count = 0;
	ibool = 1;
	while (s[i])
	{
		while (s[i] == c && s[i])
			i++;
		while (s[i] != c && s[i])
		{
			if (ibool == 1)
				count++;
			ibool = 0;
			i++;
		}
		ibool = 1;
	}
	return (count);
}

static size_t
	ft_splitlen(const char *str, char c)
{
	size_t	i;

	i = 0;
	while (str[i] != c && str[i])
		i++;
	return (i);
}

static char
	*ft_splitdup(const char *str, char c)
{
	char	*word;
	size_t	i;

	i = 0;
	if (!(word = (char*)malloc((ft_splitlen(str, c) + 1) * sizeof(char))))
		return (NULL);
	while (str[i] != c && str[i])
	{
		word[i] = str[i];
		i++;
	}
	word[i] = '\0';
	return (word);
}

static char
	**ft_splitfree(char **best_split, size_t j)
{
	while (j > 0)
	{
		ft_memdel((void**)&best_split[j]);
		j--;
	}
	ft_memdel((void**)best_split);
	return (NULL);
}

char
	**ft_split(const char *s, char c)
{
	char	**best_split;
	size_t	i;
	size_t	j;

	i = 0;
	j = 0;
	if (!(best_split = (char **)malloc((ft_count_words(s, c) + 1)
										* sizeof(char *))))
		return (NULL);
	while (s[i])
	{
		while (s[i] == c && s[i])
			i++;
		while (s[i] != c && s[i])
		{
			if (!(best_split[j] = ft_splitdup(s + i, c)))
				return (ft_splitfree(best_split, j));
			i += ft_splitlen(s + i, c);
			j++;
		}
	}
	best_split[j] = NULL;
	return (best_split);
}