-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
76 lines (69 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gnickel <gnickel@student.42heilbronn.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/16 11:23:17 by gnickel #+# #+# */
/* Updated: 2024/10/21 14:43:03 by gnickel ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t word_count(const char *s, char c)
{
size_t i;
size_t w_count;
i = 0;
w_count = 0;
while (s[i])
{
if (s[i] != c && (i == 0 || s[i - 1] == c))
w_count++;
i++;
}
return (w_count);
}
static char **actual_split(const char *s, char c, char **dst)
{
size_t i;
size_t sub_i;
size_t start;
i = 0;
sub_i = 0;
while (s[i])
{
if (s[i] != c && (i == 0 || s[i - 1] == c))
start = i;
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
{
dst[sub_i] = ft_substr(s, start, i - start + 1);
if (!dst[sub_i])
{
while (sub_i > 0)
free(dst[--sub_i]);
return (free(dst), NULL);
}
sub_i++;
}
i++;
}
dst[sub_i] = NULL;
return (dst);
}
char **ft_split(const char *s, char c)
{
char **dst;
if (!s)
return (NULL);
dst = (char **)malloc((word_count(s, c) + 1) * sizeof(char *));
if (!dst)
return (NULL);
dst = actual_split(s, c, dst);
if (!dst)
{
free(dst);
return (NULL);
}
return (dst);
}