-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
83 lines (74 loc) · 1.87 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
75
76
77
78
79
80
81
82
83
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tchevrie <tchevrie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/12 16:56:46 by tchevrie #+# #+# */
/* Updated: 2022/10/05 04:32:47 by tchevrie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t words;
size_t i;
words = 0;
i = 0;
while (s[i])
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
words++;
i++;
}
return (words);
}
static void fill_tab(char *new, char const *s, char c)
{
size_t i;
i = 0;
while (s[i] && s[i] != c)
{
new[i] = s[i];
i++;
}
new[i] = '\0';
}
static void set_mem(char **tab, char const *s, char c)
{
size_t count;
size_t index;
size_t i;
index = 0;
i = 0;
while (s[index])
{
count = 0;
while (s[index + count] && s[index + count] != c)
count++;
if (count > 0)
{
tab[i] = malloc(sizeof(char) * (count + 1));
if (!tab[i])
return ;
fill_tab(tab[i], (s + index), c);
i++;
index = index + count;
}
else
index++;
}
tab[i] = 0;
}
char **ft_split(char const *s, char c)
{
size_t words;
char **tab;
words = count_words(s, c);
tab = malloc(sizeof(char *) * (words + 1));
if (!tab)
return (NULL);
set_mem(tab, s, c);
return (tab);
}