-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
101 lines (91 loc) · 2.04 KB
/
ft_split.c
File metadata and controls
101 lines (91 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bmetehri <bmetehri@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/28 22:23:01 by bmetehri #+# #+# */
/* Updated: 2023/01/03 19:36:50 by bmetehri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t is_sep(char si, char c)
{
if (si == c || si == '\0')
return (1);
return (0);
}
void free_stuff(char **tab)
{
size_t i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
}
void remplir_str(char *dest, char *src, char sep)
{
size_t i;
i = 0;
while (is_sep(src[i], sep) == 0)
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}
size_t remplir_table(char **tab, char *str, char c)
{
size_t i;
size_t j;
size_t word;
i = 0;
word = 0;
while (str[i])
{
if (is_sep(str[i], c) == 1)
i++;
else
{
j = 0;
while (is_sep(str[i + j], c) == 0)
j++;
tab[word] = malloc(sizeof(char) * (j + 1));
remplir_str(tab[word], &str[i], c);
if (!tab[word])
return (1);
i += j;
word++;
}
}
return (0);
}
char **ft_split(const char *s, char c)
{
char **tab;
char *str;
size_t count;
size_t i;
i = 0;
count = 0;
str = (char *)s;
while (str[i])
{
if (is_sep(str[i], c) == 0
&& is_sep(str[i + 1], c) == 1)
count++;
i++;
}
tab = (char **)malloc(sizeof(char *) * (count + 1));
if (!tab)
return (NULL);
tab[count] = NULL;
i = remplir_table(tab, str, c);
if (i)
free_stuff(tab);
return (tab);
}