-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
103 lines (93 loc) · 2 KB
/
ft_split.c
File metadata and controls
103 lines (93 loc) · 2 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lahamoun <lahamoun@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/18 10:45:37 by lahamoun #+# #+# */
/* Updated: 2022/11/09 04:04:47 by lahamoun ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_cw(char const *str, char c)
{
int i;
int j;
i = 0;
j = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
if (str[i])
{
while (str[i] && str[i] != c)
i++;
j++;
}
}
return (j);
}
static int ft_clen(char const *str, int i, char c)
{
int j;
j = 0;
while (str[i] && str[i] != c)
{
i++;
j++;
}
return (j);
}
static void ft_remp(char const *str, char **tab, int *i, char c)
{
int j;
int k;
k = 0;
j = 0;
while (str[*i] && str[*i] != c)
{
tab[k][j] = str[*i];
(*i)++;
j++;
}
tab[k][j] = '\0';
}
static char **ft_free(char **tab, int k)
{
while (k >= 0)
{
free(tab[k]);
k--;
}
free(tab);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **tab;
int i;
int k;
i = 0;
k = 0;
if (!s)
return (NULL);
tab = malloc(sizeof(char *) * (ft_cw(s, c) + 1));
if (!tab)
return (NULL);
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
{
tab[k] = malloc(sizeof(char) * (ft_clen(s, i, c) + 1));
if (!(tab[k]))
return (ft_free(tab, k - 1));
ft_remp(s, &tab[k++], &i, c);
}
}
tab[k] = NULL;
return (tab);
}