-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
90 lines (82 loc) · 2.07 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: splattje <[email protected]> +#+ */
/* +#+ */
/* Created: 2023/10/11 11:54:47 by splattje #+# #+# */
/* Updated: 2023/10/19 12:50:07 by splattje ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wordcount(char const *s, char c)
{
int word_count;
word_count = 0;
while (*s != '\0')
{
if (*s != c)
{
word_count++;
while (*s != '\0' && *s != c)
s++;
}
if (*s != '\0')
s++;
}
return (word_count);
}
static char **ft_freemem(char **s, size_t index)
{
while (s[index] != NULL && index >= 0)
{
free(s[index]);
s[index] = NULL;
index--;
}
free(s);
s = NULL;
return (NULL);
}
static char **set_words(char const **s, char c, size_t *index, char ***words)
{
size_t len;
len = 0;
while ((*s)[len] && (*s)[len] != c)
len++;
(*words)[(*index)] = ft_substr(*s, 0, len);
if ((*words)[(*index)] == NULL)
{
*index = *index - 1;
return (ft_freemem(*words, *index));
}
(*index)++;
(*s) += len;
return ((char **)s);
}
char **ft_split(char const *s, char c)
{
size_t index;
size_t word_count;
char **words;
if (!s)
return (NULL);
word_count = ft_wordcount(s, c);
words = (char **)malloc(sizeof(char *) * (word_count + 1));
if (words == NULL)
return (NULL);
index = 0;
while (*s)
{
if (*s == c)
s++;
else
{
if (set_words(&s, c, &index, &words) == NULL)
return (NULL);
}
}
words[index] = NULL;
return (words);
}