-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
91 lines (83 loc) · 1.8 KB
/
ft_split.c
File metadata and controls
91 lines (83 loc) · 1.8 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
90
91
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nle-roux <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/01 18:45:16 by nle-roux #+# #+# */
/* Updated: 2023/11/15 11:34:08 by nle-roux ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words(char const *s, char c)
{
int trigger;
int words;
words = 0;
trigger = 1;
while (*s)
{
if (*s != c && trigger)
{
words++;
trigger = 0;
}
if (*s == c)
trigger = 1;
s++;
}
return (words);
}
static int ft_get_subsize(char const *s, char c)
{
int size;
size = 0;
while (*s)
{
if (*s == c)
break ;
size++;
s++;
}
return (size);
}
void ft_free_split(char **tab)
{
int i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
tab = NULL;
}
char **ft_split(const char *s, char c)
{
char **tab;
int i;
if (!s)
return (NULL);
tab = (char **)ft_calloc(ft_count_words(s, c) + 1, sizeof(char *));
i = 0;
if (!tab)
return (NULL);
while (*s)
{
if (*s != c)
{
tab[i] = ft_substr(s, 0, ft_get_subsize(s, c));
if (!tab[i++])
{
ft_free_split(tab);
break ;
}
s += ft_get_subsize(s, c);
}
if (*s)
s++;
}
return (tab);
}