-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
63 lines (57 loc) · 976 Bytes
/
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
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t amount;
size_t i;
amount = 0;
i = 0;
while (s[i] != '\0')
{
if (amount == 0 && s[i] != c)
amount++;
else if (s[i] != c && s[i - 1] == c)
amount++;
i++;
}
return (amount);
}
static size_t count_word_len(char const *s, char c)
{
size_t i;
size_t len;
i = 0;
len = 0;
while (s[i] == c)
i++;
while (s[i] != c && s[i])
{
len++;
i++;
}
return (len);
}
char **ft_split(char const *s, char c)
{
size_t i;
size_t j;
char **result;
size_t amount_words;
i = 0;
amount_words = count_words(s, c);
result = (char **)malloc(sizeof(char *) * (amount_words + 1));
if (result == NULL)
return (NULL);
result[amount_words] = NULL;
while (i < amount_words)
{
while (*s == c)
s++;
result[i] = malloc(sizeof(char) * (count_word_len(s, c) + 1));
j = 0;
while (*s != c && *s)
result[i][j++] = *s++;
result[i][j] = '\0';
i++;
}
return (result);
}