-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
81 lines (73 loc) · 1.75 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ialdidi <ialdidi@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/08 12:41:54 by ialdidi #+# #+# */
/* Updated: 2023/11/12 07:43:43 by ialdidi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *s, int c)
{
int cnt;
int pre;
cnt = 0;
pre = 1;
while (*s)
{
if (*s == c)
pre = 1;
else if (pre)
{
pre = 0;
cnt++;
}
s++;
}
return (cnt);
}
static void *free_memory(char **strs, int i)
{
while (i--)
free(strs[i]);
free(strs);
return (NULL);
}
static char **split(char **strs, char const *s, char c)
{
int i;
int len;
i = 0;
len = 0;
while (*s)
{
while (*s && *s == c)
s++;
if (*s)
{
len = 0;
while (s[len] && s[len] != c)
len++;
strs[i] = ft_substr(s, 0, len);
if (!strs[i])
return (free_memory(strs, i));
s += len;
i++;
}
}
strs[i] = NULL;
return (strs);
}
char **ft_split(char const *s, char c)
{
char **strs;
if (!s)
return (NULL);
strs = (char **)ft_calloc(count_words(s, c) + 1, sizeof(char *));
if (!strs)
return (NULL);
return (split(strs, s, c));
}