-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
105 lines (96 loc) · 2.08 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
100
101
102
103
104
105
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: olachgue <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/05 10:34:32 by olachgue #+# #+# */
/* Updated: 2024/11/12 10:33:40 by olachgue ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(const char *s, char c)
{
size_t count;
count = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
count++;
while (*s && *s != c)
s++;
}
}
return (count);
}
static char *add_word(const char *s, char c, size_t *index)
{
size_t start;
size_t len;
char *word;
size_t i;
len = 0;
while (s[*index] == c)
(*index)++;
start = *index;
while (s[*index] && s[*index] != c)
{
(*index)++;
len++;
}
word = (char *)malloc(sizeof(char) * (len + 1));
if (!word)
return (NULL);
i = 0;
while (i < len)
{
word[i] = s[start + i];
i++;
}
word[len] = '\0';
return (word);
}
static void free_split(char **arr)
{
size_t i;
i = 0;
if (!arr)
return ;
while (arr[i])
{
free(arr[i]);
i++;
}
free(arr);
}
char **ft_split(char const *s, char c)
{
char **split;
size_t i;
size_t index;
size_t word_count;
i = 0;
index = 0;
if (!s)
return (NULL);
word_count = count_words(s, c);
split = (char **)malloc(sizeof(char *) * (word_count + 1));
if (!split)
return (NULL);
while (i < word_count)
{
split[i] = add_word(s, c, &index);
if (!split[i])
{
free_split(split);
return (NULL);
}
i++;
}
split[i] = NULL;
return (split);
}