-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
96 lines (87 loc) · 1.96 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
96
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssacrist <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/27 11:51:59 by ssacrist #+# #+# */
/* Updated: 2020/01/08 15:44:40 by ssacrist ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count(char const *s, char c)
{
size_t i;
size_t count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
count++;
i++;
}
return (count);
}
static char *ft_word(char const *s, char c, int i)
{
char *word;
int o;
int p;
p = i;
while (p >= 0 && s[p] != c)
p--;
o = i - p;
word = (char *)malloc(sizeof(char) * (o + 1));
p = i;
while (p > 0 && s[p - 1] != c)
p--;
o = 0;
while (p <= i)
{
word[o] = s[p];
o++;
p++;
}
word[o] = '\0';
return (word);
}
static void ft_clean(char **str, int a)
{
int i;
i = 0;
while (i < a)
{
free(str[i]);
i++;
}
free(str);
}
char **ft_split(char const *s, char c)
{
char **result;
int i;
int j;
if (!s ||
!(result = (char **)malloc(sizeof(char *) * (ft_count(s, c) + 1))))
return (0);
i = 0;
j = 0;
while (s[i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
{
result[j] = ft_word(s, c, i);
if (result[j] == NULL)
{
ft_clean(result, j);
return (0);
}
j++;
}
i++;
}
result[j] = NULL;
return (result);
}