-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
72 lines (64 loc) · 1.02 KB
/
ft_split.c
File metadata and controls
72 lines (64 loc) · 1.02 KB
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
#include "libft.h"
static int ft_word_count(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i])
count++;
while (s[i] && s[i] != c)
i++;
}
return (count);
}
static char *ft_strndup(const char *s, int start, int len)
{
char *str;
int i;
str = malloc(len + 1);
i = 0;
if (!str)
return (NULL);
while (i < len)
str[i++] = s[start++];
str[i] = '\0';
return (str);
}
static char **ft_split_fill(char const *s, char c, char **res, int words)
{
int i;
int j;
int start;
i = 0;
j = 0;
start = 0;
while (s[i] && j < words)
{
while (s[i] == c)
i++;
start = i;
while (s[i] && s[i] != c)
i++;
if (i > start)
res[j++] = ft_strndup(s, start, i - start);
}
res[j] = NULL;
return (res);
}
char **ft_split(char const *s, char c)
{
char **res;
int words;
if (!s)
return (NULL);
words = ft_word_count(s, c);
res = malloc((words + 1) * sizeof(char *));
if (!res)
return (NULL);
return (ft_split_fill(s, c, res, words));
}