-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
83 lines (75 loc) · 1.83 KB
/
ft_split.c
File metadata and controls
83 lines (75 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: algungor <algungor@student.42istanbul.com.t+#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/01/26 16:23:12 by algungor #+# #+# */
/* Updated: 2026/02/09 12:56:36 by algungor ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t i;
size_t words;
i = 0;
words = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i])
words++;
while (s[i] != c && s[i])
i++;
}
return (words);
}
static void free_all(char **ptr, size_t a)
{
while (a > 0)
free(ptr[--a]);
free(ptr);
}
static int fill_ptr(char **ptr, char const *s, char c)
{
size_t i;
size_t len;
size_t x;
size_t a;
i = 0;
a = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (!s[i])
break ;
x = i;
while (s[i] != c && s[i])
i++;
len = i - x;
ptr[a] = ft_substr(s, x, len);
if (!ptr[a])
return (free_all(ptr, a), 0);
a++;
}
ptr[a] = NULL;
return (1);
}
char **ft_split(char const *s, char c)
{
char **ptr;
size_t words;
if (!s)
return (NULL);
words = count_words(s, c);
ptr = malloc(sizeof(char *) * (words + 1));
if (!ptr)
return (NULL);
if (!fill_ptr(ptr, s, c))
return (NULL);
return (ptr);
}