-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
62 lines (57 loc) · 1.65 KB
/
ft_split.c
File metadata and controls
62 lines (57 loc) · 1.65 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: isak <isak@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/05 10:05:53 by isak #+# #+# */
/* Updated: 2020/05/07 14:12:20 by isak ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *s, char c)
{
int cur_index;
int cur_state;
cur_index = 0;
cur_state = 0;
while (*s)
{
if (*s != c && cur_state == 0)
{
cur_state = 1;
cur_index++;
}
else if (*s == c)
cur_state = 0;
s++;
}
return (cur_index);
}
char **ft_split(char const *s, char c)
{
int i;
size_t word_len;
char **res_of_split;
if (!s || !(res_of_split =
(char **)malloc((count_words(s, c) + 1) * sizeof(char *))))
return (NULL);
i = 0;
while (*s)
{
while (*s == c && *s)
s++;
if (*s)
{
if (!ft_strchr(s, c))
word_len = ft_strlen(s);
else
word_len = ft_strchr(s, c) - s;
res_of_split[i++] = ft_substr(s, 0, word_len);
s = s + word_len;
}
}
res_of_split[i] = NULL;
return (res_of_split);
}