-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
98 lines (88 loc) · 2.16 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mrios-es <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/13 19:05:11 by mrios-es #+# #+# */
/* Updated: 2023/09/13 19:05:11 by mrios-es ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **alloc_parts(char *str, char c)
{
int i;
int parts_count;
int checkpoint;
char **parts;
i = 0;
parts_count = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
checkpoint = i;
while (str[i] && str[i] != c)
i++;
parts_count += i > checkpoint;
}
parts = ft_calloc(parts_count + 1, sizeof(char *));
if (!parts)
return (NULL);
return (parts);
}
static int count_valid_chars(char *str, char c)
{
int i;
i = 0;
while (str[i] && str[i] != c)
i++;
return (i);
}
static void free_parts(char **parts, int j)
{
while (j--)
free(parts[j]);
free(parts);
}
static char **fill_parts(char **parts, char *str, char c)
{
int i;
int j;
int valid_char_count;
i = 0;
j = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
valid_char_count = count_valid_chars(&str[i], c);
if (valid_char_count > 0)
{
parts[j] = ft_substr(str, i, valid_char_count);
if (!parts[j])
{
free_parts(parts, j);
return (NULL);
}
j++;
}
while (str[i] && str[i] != c)
i++;
}
return (parts);
}
char **ft_split(char const *s, char c)
{
char **parts;
char *str;
str = (char *)s;
if (!str)
return (NULL);
parts = alloc_parts(str, c);
if (!parts)
return (NULL);
parts = fill_parts(parts, str, c);
return (parts);
}