-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
121 lines (109 loc) · 2.39 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: sizerese <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/30 17:28:50 by sizerese #+# #+# */
/* Updated: 2023/08/11 19:58:59 by sizerese ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int is_sep(char c, char sep)
{
if (c == sep)
return (1);
else
return (0);
}
static int ft_countwords(const char *str, char c)
{
int sign;
int count;
sign = 0;
count = 0;
while (*str)
{
if (*str != c && sign == 0)
{
sign = 1;
count++;
}
else if (*str == c)
sign = 0;
str++;
}
return (count);
}
static int free_bird(char **arr, int k)
{
int i;
i = 0;
if (arr[k - 1] == NULL)
{
while (k > 0)
{
free(arr[k - 1]);
k--;
}
return (1);
}
return (0);
}
static int array_put(char **array, char const *s, char c)
{
int i;
int j;
int k;
i = 0;
k = 0;
while (s[i])
{
j = 0;
if (is_sep(s[i], c))
i++;
else
{
while (s[i + j] && !is_sep(s[i + j], c))
j++;
array[k++] = (char *)malloc((j + 1) * sizeof(char));
if (free_bird(array, k) == 1)
return (1);
ft_strlcpy(array[k - 1], s + i, j + 1);
}
i = i + j;
}
return (0);
}
char **ft_split(char const *s, char c)
{
char **buffer;
int word_count;
if (!s)
return (NULL);
word_count = ft_countwords(s, c);
buffer = (char **)malloc((word_count + 1) * sizeof(char *));
if (!buffer)
return (NULL);
if (array_put(buffer, s, c))
{
free(buffer);
return (NULL);
}
buffer[word_count] = NULL;
return (buffer);
}
// int main(void)
// {
// char **array;
// char const str[] = " hello zzzz zz z ";
// int i;
// i = 0;
// array = ft_split(str, ' ');
// for(int i=0;i< ft_countwords(str, ' ');i++)
// {
// printf("%s\n", array[i]);
// }
// return (0);
// }