-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
executable file
·95 lines (85 loc) · 1.99 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
88
89
90
91
92
93
94
95
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yhebbat <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/13 19:13:34 by yhebbat #+# #+# */
/* Updated: 2021/01/21 16:10:31 by yhebbat ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
#include "get_next_line.h"
static int words_counter(char const *s, char c)
{
int i;
int w;
i = 0;
w = 0;
while (s[i])
{
if (s[i] == c && s[i])
i++;
else if (s[i] != c && s[i])
{
w++;
i++;
while (s[i] != c && s[i])
i++;
}
}
return (w);
}
static size_t word_length(char const *s, char c)
{
int i;
i = 0;
while (s[i] != '\0' && s[i] != c)
i++;
return (i);
}
static void clean(char **split, int c)
{
while (c >= 0)
{
free(split[c]);
c--;
}
free(split);
}
static char *next_word(const char *s, char c)
{
int i;
i = 0;
while (*s && *s == c)
s++;
return ((char *)s);
}
char **ft_split(char const *s, char c)
{
size_t i;
size_t words;
char **split;
i = 0;
if (!s)
return (NULL);
words = words_counter((char *)s, c);
split = (char **)malloc((words + 1) * sizeof(char*));
if (split == NULL)
return (NULL);
while (i < words)
{
s = next_word(s, c);
split[i] = ft_substr(s, 0, word_length(s, c));
if (split[i] == NULL)
{
clean(split, i);
return (NULL);
}
i++;
s += word_length(s, c);
}
split[words] = NULL;
return (split);
}