-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
128 lines (111 loc) · 2.5 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
122
123
124
125
126
127
128
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ledias-d <[email protected]> #+# +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024-10-11 12:56:54 by ledias-d #+# #+# */
/* Updated: 2024-10-11 12:56:54 by ledias-d ### ########.rio */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(const char *s, char c)
{
int i;
size_t j;
j = 0;
i = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i])
j++;
while (s[i] != c && s[i])
i++;
}
return (j);
}
static int malloc_word(char **ptr, int y, size_t len)
{
int i;
i = 0;
ptr[y] = (char *)malloc((len + 1) * sizeof(char));
if (!ptr[y])
{
while (i < y)
free(ptr[i++]);
free(ptr);
return (1);
}
return (0);
}
static int fill_word(char **ptr, const char *s, char c)
{
int y;
size_t len;
const char *start;
y = 0;
while (*s)
{
len = 0;
while (*s == c && *s)
++s;
start = s;
while (*s != c && *s)
{
++s;
++len;
}
if (len)
{
if (malloc_word(ptr, y, len))
return (1);
ft_strlcpy(ptr[y], start, len + 1);
y++;
}
}
return (0);
}
char **ft_split(const char *s, char c)
{
char **ptr;
size_t count;
if (!s)
return (NULL);
count = count_words(s, c);
ptr = (char **)malloc((count + 1) * sizeof (char *));
if (!ptr)
return (NULL);
ptr[count] = NULL;
if (fill_word(ptr, s, c))
return (NULL);
return (ptr);
}
/*#include <stdio.h>
int main(void)
{
char **result;
int i;
char *str = "Hello 42 school of coding";
char delimiter = ' ';
result = ft_split(str, delimiter);
if (!result)
{
printf("Error: split returned NULL\n");
return (1);
}
printf("Split result for string: \"%s\"\n", str);
i = 0;
while (result[i])
{
printf("Word %d: %s\n", i + 1, result[i]);
i++;
}
i = 0;
while (result[i])
free(result[i++]);
free(result);
return 0;
}*/