-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
102 lines (91 loc) · 2.16 KB
/
ft_split.c
File metadata and controls
102 lines (91 loc) · 2.16 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: marcrodr < marcrodr@student.42sp.org.br +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/21 12:29:01 by user42 #+# #+# */
/* Updated: 2022/02/10 16:45:39 by marcrodr ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t get_wordsnum(const char *s, char c)
{
int is_word;
size_t words;
words = 0;
is_word = 0;
while (*s)
{
if (!is_word && *s != c)
{
is_word = 1;
words++;
}
else if (is_word && *s == c)
is_word = 0;
s++;
}
return (words);
}
size_t get_wordlen(const char *s, char c)
{
size_t offset;
offset = 0;
while (s[offset] && s[offset] != c)
offset++;
return (offset);
}
char *worddup(const char *s, size_t len)
{
char *str;
size_t offset;
str = malloc(len + 1);
if (str == NULL)
return (NULL);
offset = 0;
while (offset < len)
{
str[offset] = s[offset];
offset++;
}
str[offset] = '\0';
return (str);
}
static void *kill(char **res, size_t stop)
{
size_t counter;
counter = 0;
while (counter < stop)
free(res[counter]);
free(res);
return (NULL);
}
char **ft_split(const char *s, char c)
{
char **res;
size_t len;
size_t words;
size_t counter;
if (s == NULL)
return (NULL);
words = get_wordsnum(s, c);
res = malloc((words + 1) * sizeof(char *));
if (res == NULL)
return (NULL);
counter = 0;
while (counter < words)
{
len = get_wordlen(s, c);
if (len)
{
res[counter] = worddup(s, len);
if (res[counter++] == NULL)
return (kill(res, counter - 1));
}
s += len + 1;
}
res[counter] = NULL;
return (res);
}