-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
89 lines (79 loc) · 1.96 KB
/
Copy pathft_split.c
File metadata and controls
89 lines (79 loc) · 1.96 KB
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: rvan-sch <[email protected]> +#+ */
/* +#+ */
/* Created: 2019/11/22 20:56:03 by rvan-sch #+# #+# */
/* Updated: 2019/11/22 21:04:24 by rvan-sch ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_split_length(const char *s, char c)
{
size_t i;
i = 0;
while (s[i] && s[i] != c)
{
i++;
}
return (i);
}
static const char *ft_next_split(char const *s, char c)
{
while (*s && *s == c)
s++;
return (s);
}
static size_t ft_count_splits(char const *s, char c)
{
size_t n;
n = 0;
s = ft_next_split(s, c);
while (*s)
{
s = s + ft_split_length(s, c);
s = ft_next_split(s, c);
n++;
}
return (n);
}
static void ft_clean(char **split)
{
size_t i;
i = 0;
while (split[i])
{
free(split[i]);
i++;
}
free(split);
}
char **ft_split(const char *s, char c)
{
char **table;
size_t i;
size_t split_amount;
if (!s)
return (NULL);
split_amount = ft_count_splits(s, c);
table = (char **)malloc((split_amount + 1) * sizeof(char *));
if (table == NULL)
return (NULL);
i = 0;
while (i < split_amount)
{
s = ft_next_split(s, c);
table[i] = ft_substr(s, 0, ft_split_length(s, c));
if (table[i] == NULL)
{
ft_clean(table);
return (NULL);
}
i++;
s = s + ft_split_length(s, c);
}
table[split_amount] = NULL;
return (table);
}