-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
81 lines (74 loc) · 1.81 KB
/
ft_split.c
File metadata and controls
81 lines (74 loc) · 1.81 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: nhan <necat.han42@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/24 19:35:00 by nhan #+# #+# */
/* Updated: 2023/12/08 13:57:06 by nhan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_free_tab(char **tab)
{
int i;
if (!tab)
return (NULL);
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
return (NULL);
}
static int ft_count_word(char const *s, char c)
{
int i;
int count;
int tracker;
i = 0;
count = 0;
tracker = 0;
while (s && s[i] != '\0')
{
if (s[i] == c)
tracker = 0;
else if (s[i] != c && tracker == 0)
{
count++;
tracker = 1;
}
i++;
}
return (count);
}
char **ft_split(char const *s, char c)
{
char **tab_str;
int i;
int j;
int k;
if (!s)
return (NULL);
i = 0;
j = 0;
tab_str = (char **) malloc((ft_count_word(s, c) + 1) * sizeof(char *));
if (!tab_str)
return (0);
while (j < ft_count_word(s, c))
{
while (s[i] == c && s[i])
i++;
k = i;
while (s[i] != '\0' && s[i] != c)
i++;
tab_str[j++] = ft_substr(s, k, i - k);
if (!tab_str[j - 1])
return (ft_free_tab(tab_str));
}
tab_str[j] = NULL;
return (tab_str);
}