-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
102 lines (91 loc) · 2.08 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
97
98
99
100
101
102
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: kfu <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/11/11 12:17:08 by kfu #+# #+# */
/* Updated: 2021/05/05 15:29:43 by kfu ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static void *ft_free(char **split, int i)
{
int j;
j = 0;
while (j < i)
{
free(split[j]);
j++;
}
free(split);
return (NULL);
}
static int ft_countwords(char const *s, char c)
{
int i;
int words;
words = 0;
i = 0;
while (s[i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
words++;
i++;
}
return (words);
}
static int ft_wordslen(char const *s, char c)
{
int i;
int len;
i = 0;
len = 0;
while (s[i] != c && s[i] != '\0')
{
i++;
len++;
}
return (len);
}
static char **fill(char **split, const char *s, char c, int words)
{
int i;
int j;
int len;
i = 0;
while (i < words)
{
while (*s == c)
s++;
len = ft_wordslen(s, c);
split[i] = (char *)malloc(sizeof(char) * (len + 1));
if (split[i] == NULL)
return (ft_free(split, i));
j = 0;
while (j < len)
{
split[i][j] = *s;
s++;
j++;
}
split[i][j] = '\0';
i++;
}
split[i] = NULL;
return (split);
}
char **ft_split(char const *s, char c)
{
char **split;
int words;
if (!s)
return (NULL);
words = ft_countwords(s, c);
split = (char **)malloc(sizeof(char *) * (words + 1));
if (split == NULL)
return (NULL);
split = fill(split, s, c, words);
return (split);
}