-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
105 lines (94 loc) · 2.04 KB
/
ft_split.c
File metadata and controls
105 lines (94 loc) · 2.04 KB
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: alucas-e <alucas-e@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/25 11:26:42 by alucas-e #+# #+# */
/* Updated: 2024/10/31 11:59:07 by alucas-e ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void free_arr(char **arr, size_t size)
{
size_t i;
i = 0;
while (i < size)
{
free(arr[i]);
i++;
}
free(arr);
}
static size_t word_len(char const *s, char c)
{
size_t len;
len = 0;
while (s[len] && s[len] != c)
len++;
return (len);
}
static char *get_word(char const *s, char c)
{
char *str;
size_t len;
size_t i;
len = word_len(s, c);
str = (char *)malloc((len + 1) * sizeof(char));
if (!str)
return (NULL);
i = 0;
while (i < len)
{
str[i] = *s;
s++;
i++;
}
str[i] = '\0';
return (str);
}
static size_t word_count(char const *s, char c)
{
size_t cont;
cont = 0;
while (*s != '\0')
{
if (*s == c)
s++;
else
{
while (*s != c && *s != '\0')
s++;
cont++;
}
}
return (cont);
}
char **ft_split(char const *s, char c)
{
size_t i;
char **arr;
if (!s)
return (NULL);
arr = (char **)malloc((word_count(s, c) + 1) * sizeof(char *));
if (!arr)
return (NULL);
i = 0;
while (*s != '\0')
{
while (*s && *s == c)
s++;
if (*s)
{
arr[i] = get_word(s, c);
if (!arr[i])
return (free_arr(arr, i), NULL);
i++;
}
while (*s && *s != c)
s++;
}
arr[i] = NULL;
return (arr);
}