-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
95 lines (87 loc) · 1.95 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fraqioui <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/07 11:39:06 by fraqioui #+# #+# */
/* Updated: 2022/10/20 16:28:34 by fraqioui ### ########.fr */
/* */
/* ************************************************************************** */
#include"libft.h"
static char **ft_alloc_fail(char **arr)
{
unsigned int i;
i = 0;
while (arr[i])
free(arr[i++]);
free(arr);
return (NULL);
}
static int ft_words(const char *s2, char c)
{
int i;
int word;
i = 0;
word = 0;
while (s2[i])
{
if (s2[i] == c)
i++;
else
{
word++;
while (s2[i] != c && s2[i])
i++;
}
}
return (word);
}
static char *ft_fillout(const char *s1, int *j, char c)
{
char *new;
size_t len;
int i;
len = 0;
while (s1[*j] == c)
(*j)++;
i = *j;
while (s1[i] && s1[i] != c)
{
len++;
i++;
}
new = malloc(sizeof(char) * (len + 1));
if (!new)
return (NULL);
i = 0;
while (s1[*j] && s1[*j] != c)
new[i++] = s1[(*j)++];
new[i] = '\0';
return (new);
}
char **ft_split(char const *s, char c)
{
char **t_arr;
int i;
int wc;
int j;
i = 0;
j = 0;
if (!s)
return (NULL);
wc = ft_words(s, c);
t_arr = malloc(sizeof(char *) * (wc + 1));
if (!t_arr)
return (NULL);
while (j < wc)
{
t_arr[j] = ft_fillout(s, &i, c);
if (!t_arr[j])
return (ft_alloc_fail(t_arr));
j++;
}
t_arr[j] = 0;
return (t_arr);
}