-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathft_split.c
84 lines (75 loc) · 2.05 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gamarcha <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/15 21:19:14 by gamarcha #+# #+# */
/* Updated: 2021/04/15 21:19:14 by gamarcha ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *str, char sep)
{
int count;
int i;
count = 0;
i = 0;
while (str[i])
{
while (str[i] && str[i] == sep)
i++;
if (str[i] && str[i] != sep)
count++;
while (str[i] && str[i] != sep)
i++;
}
return (count);
}
static char *allocate_string(char const *s, char c)
{
char *str;
int j;
j = 0;
while (s[j] && s[j] != c)
j++;
str = (char *)malloc(j + 1);
if (str == 0)
return (0);
return (str);
}
static char **split_words(char const *s, char c, char **strs, int len)
{
int i;
int j;
i = 0;
while (i < len)
{
while (*s && *s == c)
s++;
strs[i] = allocate_string(s, c);
if (strs[i] == 0)
return (ft_free_strs(strs, i));
j = 0;
while (*s && *s != c)
strs[i][j++] = *s++;
strs[i++][j] = 0;
}
strs[i] = 0;
return (strs);
}
char **ft_split(char const *s, char c)
{
char **strs;
int len;
if (s == 0)
return (0);
len = count_words(s, c);
strs = (char **)malloc(sizeof(char *) * (len + 1));
if (strs == 0)
return (0);
if (split_words(s, c, strs, len) == 0)
return (0);
return (strs);
}