-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
89 lines (81 loc) · 1.87 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yeonhkim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/13 21:47:47 by yeonhkim #+# #+# */
/* Updated: 2022/07/23 10:42:39 by yeonhkim ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_word(char const *s, char c)
{
int count;
int flag;
count = 0;
flag = 1;
while (*s)
{
if (flag && *s != c)
{
count++;
flag = 0;
}
else if (*s == c)
flag = 1;
s++;
}
return (count);
}
static char *dup_until_c(char const *s, char c)
{
char *dst;
int len;
int i;
len = 0;
while (s[len] && s[len] != c)
len++;
dst = malloc(sizeof(char) * (len + 1));
if (!dst)
return (NULL);
i = 0;
while (*s && *s != c)
dst[i++] = *s++;
dst[i] = '\0';
return (dst);
}
void *free_all(char **dst)
{
while (*dst)
free(*dst++);
free(dst);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **dst;
int idx;
int flag;
dst = malloc(sizeof(char *) * (count_word(s, c) + 1));
if (!dst)
return (NULL);
idx = 0;
flag = 1;
while (*s)
{
if (flag && *s != c)
{
dst[idx] = dup_until_c(s, c);
if (!dst[idx++])
return (free_all(dst));
flag = 0;
}
else if (*s == c)
flag = 1;
s++;
}
dst[idx] = NULL;
return (dst);
}