-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
90 lines (82 loc) · 2.02 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kalmheir <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/03 13:33:22 by kalmheir #+# #+# */
/* Updated: 2021/10/06 14:25:36 by kalmheir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int word_len(char const *str, char sep)
{
int n;
n = 0;
while (str[n] && str[n] != sep)
n++;
return (n);
}
static int count_words(char const *str, char sep)
{
if (!*str)
return (0);
while (*str && *str == sep)
str++;
if (!*str)
return (0);
while (*str && *str != sep)
str++;
if (!*str)
return (1);
else
return (1 + count_words(str, sep));
}
static char **returner(char const *str)
{
char **result;
if (!str)
{
result = malloc(sizeof(char *));
if (!result)
return (0);
result[0] = 0;
return (result);
}
else
{
result = malloc(sizeof(char *) * 2);
if (!result)
return (0);
result[0] = ft_strdup(str);
result[1] = 0;
return (result);
}
}
char **ft_split(char const *s, char c)
{
char **result;
int words;
int i;
if (!s || !*s)
return (returner(0));
if (!c)
return (returner(s));
words = count_words(s, c);
i = 0;
result = malloc((words + 1) * sizeof(char *));
if (!result)
return (0);
while (i < words)
{
while (*s && *s == c)
s++;
if (!*s)
break ;
result[i++] = ft_substr(s, 0, word_len(s, c));
s += word_len(s, c);
}
result[i] = 0;
return (result);
}