-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
81 lines (73 loc) · 1.79 KB
/
ft_split.c
File metadata and controls
81 lines (73 loc) · 1.79 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tjeunet <tjeunet@student.42barcelo> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/23 09:48:20 by tjeunet #+# #+# */
/* Updated: 2022/09/28 20:04:39 by tjeunet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_word(char const *s, char c)
{
int i;
int word_count;
i = 0;
word_count = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
word_count++;
while (s[i] && s[i] != c)
i++;
}
return (word_count);
}
static int ft_word_len(char const *s, char c, int i)
{
int len;
len = 0;
while (s[i] != c && s[i])
{
len++;
i++;
}
return (len);
}
static void ft_free_all(char **tab, int j)
{
while (j-- > 0)
free(tab[j]);
free(tab);
}
char **ft_split(char const *s, char c)
{
int i;
char **tab;
int len;
int j;
i = 0;
j = -1;
tab = (char **)malloc(sizeof(char *) * (ft_count_word(s, c) + 1));
if (!tab)
return (NULL);
while (++j < ft_count_word(s, c))
{
while (s[i] == c)
i++;
len = ft_word_len(s, c, i);
tab[j] = ft_substr(s, i, len);
if (!tab[j])
{
ft_free_all(tab, j);
return (NULL);
}
i += len;
}
tab[j] = 0;
return (tab);
}