-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
72 lines (65 loc) · 1.69 KB
/
ft_split.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lrocca <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/15 22:10:43 by lrocca #+# #+# */
/* Updated: 2021/07/06 17:59:12 by lrocca ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wcount(char const *s, char c)
{
int count;
count = 0;
while (s && *s)
{
if (*s != c)
{
count++;
while (*s && *s != c)
s++;
}
else
s++;
}
return (count);
}
static char **free_split(char **array)
{
int i;
i = 0;
while (array && array[i])
free(array[i++]);
free(array);
return (NULL);
}
char **ft_split(char const *s, char c)
{
size_t i;
char *start;
char **array;
array = malloc((ft_wcount(s, c) + 1) * sizeof(char *));
if (!s || !array)
return (free_split(array));
i = 0;
while (*s)
{
if (*s != c)
{
start = (char *)s;
while (*s && *s != c)
s++;
array[i] = malloc((s - start) + 1);
if (!array[i])
return (free_split(array));
ft_strlcpy(array[i++], start, s - start + 1);
}
else
s++;
}
array[i] = 0;
return (array);
}