-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
94 lines (84 loc) · 2.21 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edboutil <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/24 11:42:07 by edboutil #+# #+# */
/* Updated: 2022/12/07 12:34:05 by edboutil ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *str, char charset)
{
int i;
int words;
words = 0;
i = 0;
while (str[i] != '\0')
{
if ((str[i + 1] == charset || str[i + 1] == '\0') == 1
&& (str[i] == charset || str[i] == '\0') == 0)
words++;
i++;
}
return (words);
}
static void write_word(char *dest, const char *from, char charset)
{
int i;
i = 0;
while ((from[i] == charset || from[i] == '\0') == 0)
{
dest[i] = from[i];
i++;
}
dest[i] = '\0';
}
static int free_split(char **str, int size)
{
while (size >= 0)
free(str[size--]);
free(str);
return (-1);
}
static int write_split(char **split, const char *str, char charset)
{
int i;
int j;
int word;
word = 0;
i = 0;
while (str[i] != '\0')
{
if ((str[i] == charset || str[i] == '\0') == 1)
i++;
else
{
j = 0;
while ((str[i + j] == charset || str[i + j] == '\0') == 0)
j++;
split[word] = (char *)malloc(sizeof(char) * (j + 1));
if (!split)
return (free_split(split, word - 1));
write_word(split[word], str + i, charset);
i += j;
word++;
}
}
return (0);
}
char **ft_split(const char *str, char c)
{
char **res;
int words;
words = count_words(str, c);
res = (char **)malloc(sizeof(char *) * (words + 1));
if (!res)
return (NULL);
res[words] = 0;
if (write_split(res, str, c) == -1)
return (NULL);
return (res);
}