-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
95 lines (86 loc) · 2.07 KB
/
Copy pathft_split.c
File metadata and controls
95 lines (86 loc) · 2.07 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: csekakul <csekakul@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/01/13 14:00:25 by csekakul #+# #+# */
/* Updated: 2026/01/23 08:12:12 by csekakul ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int is_delim(char c, char delim)
{
return (c == delim);
}
static int count_words(const char *str, char delim)
{
int count;
count = 0;
while (*str)
{
while (*str && is_delim(*str, delim))
str++;
if (*str)
{
count++;
while (*str && !is_delim(*str, delim))
str++;
}
}
return (count);
}
static char *alloc_word(const char *str, char delim)
{
int len;
int i;
char *word;
len = 0;
i = 0;
while (str[len] && !is_delim(str[len], delim))
len++;
word = (char *)malloc((len + 1) * sizeof(char));
if (!word)
return (NULL);
while (i < len)
{
word[i] = str[i];
i++;
}
word[len] = '\0';
return (word);
}
static void free_all(char **result, int i)
{
while (i >= 0)
free(result[i--]);
free(result);
}
char **ft_split(char const *s, char c)
{
char **result;
int i;
i = 0;
if (!s)
return (NULL);
result = malloc((count_words(s, c) + 1) * sizeof(char *));
if (!result)
return (NULL);
while (*s)
{
while (*s && is_delim(*s, c))
s++;
if (*s)
{
result[i] = alloc_word(s, c);
if (!result[i])
return (free_all(result, i - 1), NULL);
i++;
while (*s && !is_delim(*s, c))
s++;
}
}
result[i] = NULL;
return (result);
}