-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
92 lines (83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: chonorat <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/22 16:25:00 by chonorat #+# #+# */
/* Updated: 2022/11/22 16:27:02 by chonorat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_word(char const *s, char c)
{
size_t count;
size_t index;
index = 0;
count = 0;
while (s[index] == c && s[index])
index++;
while (s[index])
{
if (s[index] == c)
{
count++;
while (s[index] == c && s[index])
index++;
}
else
index++;
}
if (index > 0 && s[index - 1] != c)
count++;
return (count);
}
static size_t count_char(char const *s, char c, int index)
{
size_t count;
count = 0;
while (s[index] && s[index] != c)
{
count++;
index++;
}
return (count);
}
static char **free_malloc(char **str)
{
int index;
index = 0;
while (str[index])
{
free(str[index]);
index++;
}
free(str);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **new_str;
size_t index;
size_t index_j;
if (!s)
return (NULL);
new_str = (char **)malloc((count_word(s, c) + 1) * sizeof(char *));
if (!new_str)
return (NULL);
index = 0;
index_j = 0;
while (index_j < count_word(s, c))
{
while (s[index] == c)
index++;
new_str[index_j] = ft_substr(s, index, count_char(s, c, index));
if (!new_str[index_j])
return (free_malloc(new_str));
index += count_char(s, c, index);
index_j++;
}
new_str[index_j] = 0;
return (new_str);
}