-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
103 lines (94 loc) · 2.41 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: msubtil- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/12 15:31:45 by msubtil- #+# #+# */
/* Updated: 2022/05/11 22:33:54 by msubtil- ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_strlen_split(char const *s, char c)
{
size_t len;
len = 0;
while (*s != c && *s != '\0')
{
len++;
s++;
}
return (len);
}
static size_t ft_get_substrs_nb(char const *s, char c)
{
size_t substrs_nb;
short word_state;
substrs_nb = 0;
word_state = 0;
while (*s)
{
if (word_state == 0)
{
if (*s != c)
{
word_state = 1;
substrs_nb++;
}
}
else
if (*s == c)
word_state = 0;
s++;
}
return (substrs_nb);
}
static void ft_fill_table(char **dst, char const *s, char c)
{
short word_state;
size_t str_index;
word_state = 0;
str_index = 0;
while (*++s)
{
if (word_state == 0 && *s != c)
{
word_state = 1;
*dst = malloc(sizeof(char) * (ft_strlen_split(s, c) + 1));
(*dst)[str_index++] = *s;
}
else if (word_state == 1 && *s == c)
{
word_state = 0;
(*dst)[str_index++] = '\0';
str_index = 0;
dst++;
}
else if (word_state == 1 && *s != c)
(*dst)[str_index++] = *s;
}
if (word_state == 1)
(*dst)[str_index++] = '\0';
}
char **ft_split(char const *s, char c)
{
char **table;
char delimiter_set[1];
size_t substrings_nb;
if (s == NULLPTR)
return ((char **) NULLPTR);
substrings_nb = ft_get_substrs_nb(s, c);
table = (char **) malloc(sizeof(char *) * (substrings_nb + 1));
if (table == NULLPTR)
return ((char **) NULLPTR);
if (substrings_nb > 1)
ft_fill_table(table, --s, c);
else if (substrings_nb == 1)
{
delimiter_set[0] = c;
table[0] = ft_strtrim((char *) s, delimiter_set);
}
table[substrings_nb] = NULLPTR;
return (table);
}