-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
83 lines (75 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
77
78
79
80
81
82
83
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcatal-d <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/23 18:06:26 by mcatal-d #+# #+# */
/* Updated: 2022/11/11 15:52:58 by mcatal-d ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int nombre_lettre(const char *str, char c)
{
int i;
i = 0;
while (str[i] && str[i] != c)
++i;
return (i);
}
static int nombre_mots(const char *str, char c)
{
int mots;
int sep;
mots = 0;
sep = 1;
while (*str)
{
if (*str == c)
sep = 1;
else if (sep == 1)
{
mots++;
sep = 0;
}
str++;
}
return (mots);
}
static char **error(char **tab, int i)
{
while (i < 0)
{
free(tab[i]);
i--;
}
free(tab);
return (NULL);
}
char **ft_split(const char *str, char c)
{
char **tab;
int i;
int j;
if (str == NULL)
return (NULL);
tab = malloc(sizeof(char *) * (nombre_mots(str, c) + 1));
if (tab == NULL)
return (NULL);
i = 0;
while (nombre_mots(str, c))
{
while (*str && *str == c)
str++;
tab[i] = malloc(sizeof(char) * nombre_lettre(str, c) + 1);
if (!tab[i])
return (error(tab, i));
j = 0;
while (*str && *str != c)
tab[i][j++] = *str++;
tab[i++][j] = '\0';
}
tab[i] = 0;
return (tab);
}