-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
99 lines (91 loc) · 2.22 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
90
91
92
93
94
95
96
97
98
99
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lrafael <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/05 10:34:16 by lrafael #+# #+# */
/* Updated: 2023/12/05 10:34:49 by lrafael ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_malloc_error(char **tab)
{
size_t i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
return (NULL);
}
static size_t ft_nb_words(char const *s, char c)
{
size_t i;
size_t nb_words;
if (!s[0])
return (0);
i = 0;
nb_words = 0;
while (s[i] && s[i] == c)
i++;
while (s[i])
{
if (s[i] == c)
{
nb_words++;
while (s[i] && s[i] == c)
i++;
continue ;
}
i++;
}
if (s[i - 1] != c)
nb_words++;
return (nb_words);
}
static void ft_get_next_word(char **next_word, size_t *next_word_len, char c)
{
size_t i;
*next_word += *next_word_len;
*next_word_len = 0;
i = 0;
while (**next_word && **next_word == c)
(*next_word)++;
while ((*next_word)[i])
{
if ((*next_word)[i] == c)
return ;
(*next_word_len)++;
i++;
}
}
char **ft_split(char const *s, char c)
{
char **tab;
char *next_word;
size_t next_word_len;
size_t i;
if (!s)
return (NULL);
tab = (char **)malloc(sizeof(char *) * (ft_nb_words(s, c) + 1));
if (!tab)
return (NULL);
i = 0;
next_word = (char *)s;
next_word_len = 0;
while (i < ft_nb_words(s, c))
{
ft_get_next_word(&next_word, &next_word_len, c);
tab[i] = (char *)malloc(sizeof(char) * (next_word_len + 1));
if (!tab[i])
return (ft_malloc_error(tab));
ft_strlcpy(tab[i], next_word, next_word_len + 1);
i++;
}
tab[i] = NULL;
return (tab);
}