-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
114 lines (104 loc) · 2.45 KB
/
ft_split.c
File metadata and controls
114 lines (104 loc) · 2.45 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rlamtaou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/06 18:10:58 by rlamtaou #+# #+# */
/* Updated: 2023/11/24 01:28:58 by rlamtaou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_countword(char *s1, char c)
{
size_t sum;
sum = 0;
while (*s1)
{
while (*s1 == c && *s1 != '\0')
s1++;
if (*s1 != c && *s1 != '\0')
sum++;
while (*s1 != c && *s1 != '\0')
s1++;
}
return (sum);
}
static char *ft_initil(char *s, char c)
{
size_t x;
char *ptr;
x = 0;
while (s[x] != c && s[x] != '\0')
x++;
ptr = malloc((x + 1) * sizeof(char));
if (!ptr)
return (NULL);
x = 0;
while (s[x] != c && s[x] != '\0')
{
ptr[x] = s[x];
x++;
}
ptr[x] = '\0';
return (ptr);
}
static char **ft_free_all(char **ptr, size_t end)
{
size_t start;
start = 0;
while (start < end)
{
free(ptr[start]);
ptr[start] = NULL;
start++;
}
free(ptr);
ptr = NULL;
return (NULL);
}
static char **ft_split2(char **ptr, char *s, char c)
{
size_t x;
x = 0;
while (*s)
{
while (*s == c && *s != '\0')
s++;
if (*s != '\0')
{
ptr[x] = ft_initil((char *)s, c);
if (ptr[x++] == NULL)
return (ft_free_all(ptr, x));
}
while (*s != c && *s != '\0')
s++;
while (*s == c && *s != '\0')
s++;
}
ptr[x] = NULL;
return (ptr);
}
char **ft_split(char const *s, char c)
{
char **ptr;
size_t total;
if (!s)
return (ft_calloc(1, sizeof(char)));
total = ft_countword((char *)s, c);
ptr = malloc(((total + 1) * sizeof(char *)));
if (!ptr)
return (NULL);
ptr = ft_split2(ptr, (char *)s, c);
return (ptr);
}
// #include<stdio.h>
// int main() {
// char **res = ft_split("Hello World Man", ' ');
// printf("%s\n", res[0]);
// printf("%s\n", res[1]);
// printf("%s\n", res[2]);
// ft_free_all(res, 3);
// return 0;
// }