-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
87 lines (79 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: doley <doley@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/09 18:44:35 by doley #+# #+# */
/* Updated: 2024/10/11 22:34:21 by doley ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words(const char *str, char c)
{
int count;
int in_word;
count = 0;
in_word = 0;
while (*str)
{
if (*str != c && !in_word)
{
in_word = 1;
count++;
}
else if (*str == c)
in_word = 0;
str++;
}
return (count);
}
static void ft_free_tab(char **tab, int i)
{
while (i >= 0)
{
free(tab[i]);
i--;
}
free(tab);
}
static int ft_fill_tab(char **tab, const char *s, char c)
{
int i;
size_t len;
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
if (!ft_strchr(s, c))
len = ft_strlen(s);
else
len = ft_strchr(s, c) - s;
tab[i++] = ft_substr(s, 0, len);
if (!tab[i - 1])
{
ft_free_tab(tab, i - 2);
return (-1);
}
s += len;
}
}
tab[i] = NULL;
return (0);
}
char **ft_split(char const *s, char c)
{
char **tab;
if (!s)
return (NULL);
tab = malloc(sizeof(char *) * (ft_count_words(s, c) + 1));
if (!tab)
return (NULL);
if (ft_fill_tab(tab, s, c) == -1)
return (NULL);
return (tab);
}