-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
85 lines (77 loc) · 1.9 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adamarqu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/21 11:40:13 by adamarqu #+# #+# */
/* Updated: 2024/10/21 11:40:14 by adamarqu ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t count;
int in_word;
count = 0;
in_word = 0;
while (*s)
{
if (*s != c && !in_word)
{
in_word = 1;
count++;
}
else if (*s == c)
in_word = 0;
s++;
}
return (count);
}
static char *get_next_word(char const **s, char c)
{
char const *word_start;
size_t word_len;
word_start = *s;
word_len = 0;
while (**s && **s != c)
{
(*s)++;
word_len++;
}
return (ft_substr(word_start, 0, word_len));
}
static void *free_split(char **split, size_t count)
{
while (count--)
free(split[count]);
free(split);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **result;
size_t word_count;
size_t i;
if (!s)
return (NULL);
word_count = count_words(s, c);
result = ft_calloc(word_count + 1, sizeof(char *));
if (!result)
return (NULL);
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
result[i] = get_next_word(&s, c);
if (!result[i])
return (free_split(result, i));
i++;
}
}
return (result);
}