-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
80 lines (71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nenvoy <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 15:37:44 by nenvoy #+# #+# */
/* Updated: 2021/11/26 15:37:44 by nenvoy ### ########.fr */
/* */
/* ************************************************************************** */
#include "pipex.h"
static size_t ft_words_count(char const *s, char c)
{
size_t i;
size_t words;
words = 0;
i = 0;
while (s[i] != '\0')
{
if (s[i++] == c)
continue ;
words++;
while (s[i] != c)
if (s[i++] == '\0')
return (words);
}
return (words);
}
static size_t ft_words_len(const char *s, char sep)
{
size_t i;
i = 0;
while (s[i] != '\0' && s[i] != sep)
i++;
return (i);
}
static char **ft_free(char **arr)
{
size_t i;
i = 0;
while (arr[i])
free(arr[i++]);
free (arr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **arr;
size_t i;
size_t j;
i = 0;
j = 0;
if (s == NULL)
return (NULL);
arr = malloc((ft_words_count(s, c) + 1) * sizeof(char *));
if (arr == NULL)
return (NULL);
while (s[i] != '\0')
{
if (s[i++] == c)
continue ;
--i;
arr[j] = ft_substr(s, i, ft_words_len(&s[i], c));
if (arr[j++] == NULL)
return (ft_free (arr));
i += ft_words_len(&s[i], c);
}
arr[j] = 0;
return (arr);
}