-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathft_split.c
101 lines (92 loc) · 2.29 KB
/
ft_split.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: daelee <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/05 12:38:12 by daelee #+# #+# */
/* Updated: 2020/04/09 11:00:41 by daelee ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_malloc_error(char **tab)
{
unsigned int i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
return (NULL);
}
static unsigned int ft_get_nb_strs(char const *s, char c)
{
unsigned int i;
unsigned int nb_strs;
if (!s[0])
return (0);
i = 0;
nb_strs = 0;
while (s[i] && s[i] == c)
i++;
while (s[i])
{
if (s[i] == c)
{
nb_strs++;
while (s[i] && s[i] == c)
i++;
continue ;
}
i++;
}
if (s[i - 1] != c)
nb_strs++;
return (nb_strs);
}
static void ft_get_next_str(char **next_str, unsigned int *next_str_len,
char c)
{
unsigned int i;
*next_str += *next_str_len;
*next_str_len = 0;
i = 0;
while (**next_str && **next_str == c)
(*next_str)++;
while ((*next_str)[i])
{
if ((*next_str)[i] == c)
return ;
(*next_str_len)++;
i++;
}
}
char **ft_split(char const *s, char c)
{
char **tab;
char *next_str;
unsigned int next_str_len;
unsigned int nb_strs;
unsigned int i;
if (!s)
return (NULL);
nb_strs = ft_get_nb_strs(s, c);
if (!(tab = (char **)malloc(sizeof(char *) * (nb_strs + 1))))
return (NULL);
i = 0;
next_str = (char *)s;
next_str_len = 0;
while (i < nb_strs)
{
ft_get_next_str(&next_str, &next_str_len, c);
if (!(tab[i] = (char *)malloc(sizeof(char) * (next_str_len + 1))))
return (ft_malloc_error(tab));
ft_strlcpy(tab[i], next_str, next_str_len + 1);
i++;
}
tab[i] = NULL;
return (tab);
}