-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strsplit.c
76 lines (69 loc) · 1.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: asarandi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/24 13:40:51 by asarandi #+# #+# */
/* Updated: 2017/09/24 14:01:05 by asarandi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
size_t i;
int n;
i = 0;
n = 0;
while (s[i])
{
while ((s[i] != 0) && (s[i] == c))
i++;
if (i < ft_strlen(s))
n++;
while ((s[i] != 0) && (s[i] != c))
i++;
}
return (n);
}
static int copy_words(char const *s, char c, char **a)
{
size_t i;
size_t k;
int j;
i = 0;
j = 0;
while (s[i])
{
while ((s[i] != 0) && (s[i] == c))
i++;
if (i == ft_strlen(s))
break ;
k = i;
while ((s[i] != 0) && (s[i] != c))
i++;
if ((a[j] = ft_memalloc((i - k + 1) * sizeof(char))) == NULL)
return (0);
ft_strncpy(a[j++], &s[k], i - k);
}
a[j] = NULL;
return (1);
}
char **ft_strsplit(char const *s, char c)
{
char **arr;
int cw;
cw = count_words(s, c);
arr = (char **)malloc((cw + 1) * sizeof(char *));
if (!arr)
return (NULL);
if (cw == 0)
{
arr[0] = NULL;
return (arr);
}
if (!copy_words(s, c, arr))
return (NULL);
return (arr);
}