-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft_strsplit.c
87 lines (80 loc) · 1.91 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smonroe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/20 20:13:34 by smonroe #+# #+# */
/* Updated: 2018/08/27 17:06:30 by smonroe ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char ft_word_count(char const *s, char c)
{
int words;
int i;
i = 0;
words = 0;
while (s[i] && s[i] == c)
i++;
while (s[i])
{
if (s[i] != c)
words++;
while (s[i] != c && s[i])
i++;
while (s[i] == c && s[i])
i++;
}
return (words);
}
static char **ft_make_2d(char const *s, char **bloc, char c)
{
int i;
int w;
int l;
if (!(bloc = (char **)malloc(sizeof(char *) * (ft_word_count(s, c) + 1))))
return (NULL);
w = 0;
i = 0;
while (s[i])
{
l = 0;
while (s[i] == c && s[i])
i++;
while (s[i] != c && s[i])
{
i++;
l++;
}
if (l)
if (!(bloc[w++] = ft_strnew(l + 1)) && s[i])
return (NULL);
}
return (bloc);
}
char **ft_strsplit(char const *s, char c)
{
int w;
int l;
char **bloc;
if (!(s && c))
return (NULL);
bloc = NULL;
if (!(bloc = ft_make_2d(s, bloc, c)))
return (NULL);
w = 0;
while (*s)
{
l = 0;
while (*s == c && *s)
s += 1;
while (*s != c && *s)
bloc[w][l++] = *s++;
if (l)
bloc[w++][l] = '\0';
}
bloc[w] = 0;
return (bloc);
}