-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_strsplit.c
77 lines (70 loc) · 1.95 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vbrazas <vbrazas@student.unit.ua> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/15 20:14:25 by vbrazas #+# #+# */
/* Updated: 2017/11/16 19:39:44 by vbrazas ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void find_word(size_t *i, size_t *j, char const *s, char c)
{
*i = *j;
while (s[(*i)] == c && s[(*i)])
*i = *i + 1;
*j = *i;
while (s[(*j)] != c && s[(*j)])
*j = *j + 1;
}
static char **freedom(char **buf, size_t y, char ***buff)
{
while (y)
free(buf[--y]);
free(buf);
*buff = NULL;
return (NULL);
}
static char **appropriation(char **buf, size_t wn, char const *s, char c)
{
size_t x;
size_t y;
size_t i;
size_t j;
y = 0;
j = 0;
while (y < wn)
{
x = 0;
find_word(&i, &j, s, c);
buf[y] = (char *)malloc(sizeof(char) * (j - i + 1));
if (buf[y] == NULL)
return (freedom(buf, y, &buf));
while (i < j)
buf[y][x++] = s[i++];
buf[y++][x] = '\0';
}
buf[y] = NULL;
return (buf);
}
char **ft_strsplit(char const *s, char c)
{
char **buf;
size_t wn;
size_t i;
if (!s)
return (NULL);
i = 0;
wn = 0;
if (s[0] != c && s[0])
wn++;
while (s[i++])
if (s[i - 1] == c && s[i] != c && s[i])
wn++;
buf = (char **)malloc(sizeof(char *) * (wn + 1));
if (buf == NULL)
return (NULL);
return (appropriation(buf, wn, s, c));
}