-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
85 lines (76 loc) · 1.81 KB
/
ft_split.c
File metadata and controls
85 lines (76 loc) · 1.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mhoussas <mhoussas@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/25 09:29:49 by mhoussas #+# #+# */
/* Updated: 2024/11/18 11:36:34 by mhoussas ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void *free_array(char **ptr, int len)
{
int i;
i = 0;
while (i < len)
{
free(ptr[i]);
i++;
}
free(ptr);
return (NULL);
}
static int count_word(const char *s, char c)
{
int count;
count = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
count++;
while (*s && *s != c)
s++;
}
}
return (count);
}
static int find(const char *s, char c)
{
int res;
res = 0;
while (s[res] && s[res] != c)
res++;
return (res);
}
char **ft_split(const char *s, char c)
{
char **res;
int i;
if (!s)
return (NULL);
res = (char **)malloc((count_word(s, c) + 1) * sizeof(char *));
if (!res)
return (NULL);
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
res[i] = (char *)malloc((find(s, c) + 1) * sizeof(char));
if (!res[i])
return (free_array(res, i));
ft_memcpy(res[i], s, find(s, c));
res[i++][find(s, c)] = '\0';
s += find(s, c);
}
}
res[i] = NULL;
return (res);
}