-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
78 lines (70 loc) · 1.88 KB
/
ft_split.c
File metadata and controls
78 lines (70 loc) · 1.88 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: framos-p <framos-p@student.42barcel> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/30 15:09:47 by framos-p #+# #+# */
/* Updated: 2022/06/10 10:17:52 by framos-p ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_n_words(char const *s, char c)
{
int i;
int word;
i = 0;
word = 0;
while (s[i] != '\0')
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
word++;
i++;
}
return (word);
}
char **ft_liberar(char **result, int word)
{
while (word > 0)
{
word--;
free(result[word]);
}
free(result);
return (0);
}
char **ft_recortar(char const *s, char c, char **result)
{
int i;
int word;
int start;
i = 0;
word = 0;
while (s[i] != '\0')
{
if (i == 0 && s[i] != c)
start = i;
if (i > 0 && s[i] != c && s[i - 1] == c)
start = i;
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
{
result[word] = ft_substr(s, start, (i - start) + 1);
if (!result[word])
return (ft_liberar(result, word));
word++;
}
i++;
}
result[word] = NULL;
return (result);
}
char **ft_split(char const *s, char c)
{
char **result;
result = malloc((ft_n_words(s, c) + 1) * sizeof(char *));
if (!result)
return (NULL);
result = ft_recortar(s, c, result);
return (result);
}