-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathft_split.c
74 lines (67 loc) · 1.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
#include "libft.h"
static int count_words(char *str, char c)
{
int i;
int count;
int word;
i = 0;
count = 0;
word = 0;
while (str[i] == c && str[i])
i++;
while (str[i])
{
if (str[i] != c && str[i])
word = 1;
if (str[i] == c)
{
while (str[i] == c && str[i])
i++;
if (str[i])
count++;
}
else
i++;
}
return (count + word);
}
static char *put_word(char *str, char c)
{
int i;
char *arr;
i = 0;
arr = 0;
while (str[i] && str[i] != c)
i++;
if (!(arr = (char *)malloc(sizeof(char) * (i + 1))))
return (NULL);
ft_strlcpy(arr, str, i + 1);
return (arr);
}
char **ft_split(char const *s, char c)
{
int i;
int words;
char **array;
i = -1;
if (!s)
return (NULL);
words = count_words((char *)s, c);
if (!(array = malloc(sizeof(char *) * (words + 1))))
return (NULL);
while (++i < words)
{
while (s[0] == c)
s++;
if (!(array[i] = put_word((char *)s, c)))
{
while (i > 0)
free(array[i--]);
free(array);
return (NULL);
}
s += ft_strlen(array[i]);
}
array[i] = 0;
return (array);
}