-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
87 lines (76 loc) · 1.97 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
84
85
86
87
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpouget <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/14 17:04:37 by tpouget #+# #+# */
/* Updated: 2021/04/19 15:32:04 by tpouget ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static const char *next_sep(const char *str, char sep)
{
while (*str && *str != sep)
str++;
return (str);
}
static const char *next_word(const char *str, char sep)
{
while (*str && *str == sep)
str++;
return (str);
}
static char **diralloc(const char *s, char c)
{
size_t size;
if (!s)
return (NULL);
size = 1;
s = next_word(s, c);
while (*s)
{
s = next_sep(s, c);
s = next_word(s, c);
size++;
}
return (malloc(size * sizeof(char*)));
}
char **ft_split(char const *s, char c)
{
char **dir;
const char *follower;
long i;
if (!(dir = diralloc(s, c)))
return (NULL);
s = next_word(s, c);
follower = s;
i = 0;
while (*s)
{
s = next_sep(s, c);
if (!(dir[i++] = ft_strndup(follower, s - follower)))
{
while (--i >= 0)
free(dir[i]);
free(dir);
return (NULL);
}
s = next_word(s, c);
follower = s;
}
dir[i] = NULL;
return (dir);
}
/*
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc != 3) return 1;
char **dir = ft_split(argv[1], argv[2][0]);
for(int i = 0; dir[i]; i++)
printf("%s\n", dir[i]);
return 0;
}
*/