-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
100 lines (91 loc) · 2.1 KB
/
ft_split.c
File metadata and controls
100 lines (91 loc) · 2.1 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ghuertas <ghuertas@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/10 20:39:55 by dolvin17 #+# #+# */
/* Updated: 2023/09/28 19:24:27 by ghuertas ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
/* reserva con malloc y devuelve un array de strings
separa s con c como delimitador */
static int ft_count_words(char const *s, char c)
{
int nb;
int i;
nb = 0;
i = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] != '\0')
nb++;
while (s[i] && s[i] != c)
i++;
}
return (nb);
}
static char *ft_place_word(char const *s, char c)
{
char *word;
int i;
int len;
len = 0;
while (s[len] && s[len] != c)
len++;
word = (char *)malloc(sizeof(char) * (len + 1));
if (!word)
return (NULL);
i = 0;
while (i < len)
{
word[i] = s[i];
i++;
}
word[i] = '\0';
return (word);
}
static char *ft_cpy_str(int i, char const *s, char c, char **res)
{
res[i] = ft_place_word(s, c);
if (!res[i])
{
while (i > 0)
{
i--;
free(res[i]);
}
free(res);
return (NULL);
}
return (res[i]);
}
char **ft_split(char const *s, char c)
{
int nb_words;
int i;
char **res;
if (!s)
return (NULL);
i = 0;
nb_words = ft_count_words(s, c);
res = (char **)malloc(sizeof(char *) * (nb_words + 1));
if (!res)
return (NULL);
while (i < nb_words)
{
while (*s == c)
s++;
if (*s != '\0')
res[i] = ft_cpy_str(i, s, c, res);
while (*s && *s != c)
s++;
i++;
}
res[i] = 0;
return (res);
}