-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
executable file
·68 lines (63 loc) · 1.68 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vportell <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/31 08:16:29 by vportell #+# #+# */
/* Updated: 2016/11/05 12:22:41 by vportell ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **populate_array(char **d, const char *s, char c)
{
int i;
int j;
int k;
int n;
i = -1;
n = 0;
while (s[++i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
{
j = 0;
while (s[--i] != c && i > -1)
j++;
i += (j + 1);
d[n] = (char *)malloc(sizeof(char) * (j + 2));
k = i - j;
d[n][++j] = '\0';
while (j--)
d[n][j] = s[j + k];
n++;
}
}
d[n] = 0;
return (d);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int n;
char **d;
i = -1;
j = 0;
n = 0;
if (!s)
return (NULL);
while (s[++i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
j++;
if (s[i] == c)
n++;
}
if (!(d = (char **)malloc(sizeof(char *) * (j + 1))))
return (NULL);
if (n == i)
d[0] = 0;
return (populate_array(d, s, c));
}