Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
94 lines (85 loc) · 1.95 KB
/
Copy pathft_split.c
File metadata and controls
94 lines (85 loc) · 1.95 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ttorbeyn <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/12 18:46:37 by ttorbeyn #+# #+# */
/* Updated: 2021/01/12 18:46:37 by ttorbeyn ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wordcount(char const *s, char c)
{
size_t i;
int x;
i = 0;
x = 0;
if (s[i] != c && s[i])
{
x++;
i++;
}
else if (s[i])
i++;
while (s[i] != '\0')
{
if (s[i - 1] == c && s[i] != c)
x++;
i++;
}
return (x);
}
static int ft_wordlen(char const *s, char c, size_t x)
{
size_t i;
i = 0;
while (s[x] && s[x] == c)
x++;
while (s[x] && s[x] != c)
{
x++;
i++;
}
return (i);
}
static char **ft_freeall(char **new, int i)
{
int j;
j = 0;
while (j < i && new[j])
{
free(new[j]);
j++;
}
free(new);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **new;
int i;
size_t j;
size_t x;
if (!s)
return (NULL);
if (!(new = malloc((sizeof(char *)) * (ft_wordcount(s, c) + 1))))
return (NULL);
i = 0;
x = 0;
while (i < (ft_wordcount(s, c)))
{
j = 0;
if (!(new[i] = malloc((sizeof(char) * (ft_wordlen(s, c, x) + 1)))))
return (ft_freeall(new, i));
while (s[x] && s[x] == c)
x++;
while (s[x] && s[x] != c)
new[i][j++] = s[x++];
new[i][j] = '\0';
i++;
}
new[i] = NULL;
return (new);
}