-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
121 lines (110 loc) · 2.32 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apimikov <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/06 11:43:29 by apimikov #+# #+# */
/* Updated: 2023/11/13 11:27:49 by apimikov ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
size_t word_count_char(char const *s, char c);
int write_word_char(char **arr, char const **s, char c);
void clean_array(char ***arr, size_t len);
char **ft_split(char const *s, char c)
{
size_t i;
size_t len;
char **array;
if (!s)
return (NULL);
len = word_count_char(s, c);
array = (char **)malloc((len + 1) * sizeof(char *));
if (!array)
return (NULL);
i = 0;
while (*s && i < len)
{
while ((*s == c) && *s)
s++;
if (!write_word_char(array + i, &s, c))
{
clean_array(&array, i);
return (NULL);
}
i++;
}
*(array + len) = NULL;
return (array);
}
void clean_array(char ***arr, size_t len)
{
size_t i;
i = 0;
while (i < len)
{
free(*(*arr + i));
i++;
}
free(*arr);
}
int write_word_char(char **arr, char const **s, char c)
{
char const *temp;
int len;
int i;
temp = *s;
len = 0;
while ((*temp != c) && *temp)
{
len++;
temp++;
}
if (len > 0)
{
*arr = (char *)malloc(sizeof(char) * (len + 1));
if (*arr == NULL)
return (0);
}
i = -1;
while (++i < len)
{
(*arr)[i] = **s;
(*s)++;
}
(*arr)[i] = '\0';
return (1);
}
size_t word_count_char(char const *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (s[i])
{
if (s[i] == c)
{
i++;
continue ;
}
count++;
while ((s[i] != c) && s[i])
i++;
}
return (count);
}
/*
int is_sep(char c, char *charset)
{
while (*charset)
{
if (*charset == c)
return (1);
charset++;
}
return (0);
}
*/