-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
executable file
·106 lines (95 loc) · 2.31 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ysoroko <ysoroko@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/20 09:48:32 by ysoroko #+# #+# */
/* Updated: 2020/12/03 17:40:15 by ysoroko ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wordcount(char const *str, char sep)
{
int i;
int count;
if (str == 0 || str[0] == 0)
return (0);
i = 1;
count = 0;
if (str[0] != sep)
count++;
while (str[i] != '\0')
{
if (str[i] != sep && str[i - 1] == sep)
count++;
i++;
}
return (count);
}
static char **ft_malloc(char const *str, char sep)
{
int len;
char **tab_str;
len = ft_wordcount(str, sep);
tab_str = malloc(sizeof(*tab_str) * (len + 1));
if (tab_str == 0)
{
return (0);
}
return (tab_str);
}
static int ft_next_word_count(char const *str, char sep, int i)
{
int count;
count = 0;
while (str[i] == sep && str[i] != '\0')
{
i++;
}
while (str[i] != '\0' && str[i] != sep)
{
count++;
i++;
}
return (count);
}
static char **ft_free(char **str_tab, int i)
{
int j;
j = 0;
while (j < i && str_tab[j] != 0)
{
free(str_tab[j]);
j++;
}
free(str_tab);
return (0);
}
char **ft_split(char const *str, char charset)
{
int s;
int i;
int j;
char **tab_str;
if (str == 0)
return (0);
s = 0;
i = -1;
if (!(tab_str = ft_malloc(str, charset)))
return (0);
while (++i < ft_wordcount(str, charset))
{
j = 0;
if (!(tab_str[i] = malloc(ft_next_word_count(str, charset, s) + 1)))
return (ft_free(tab_str, i));
while (str[s] != '\0' && str[s] == charset)
s++;
while (str[s] != '\0' && str[s] != charset)
tab_str[i][j++] = str[s++];
tab_str[i][j] = '\0';
}
tab_str[i] = 0;
return (tab_str);
}