-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
104 lines (95 loc) · 2.11 KB
/
ft_split.c
File metadata and controls
104 lines (95 loc) · 2.11 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mjusta <mjusta@student.42prague.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/05/28 01:42:22 by mjusta #+# #+# */
/* Updated: 2025/05/28 03:17:42 by mjusta ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(const char *s, char c)
{
size_t count;
int in_word;
count = 0;
in_word = 0;
while (*s)
{
if (*s != c && !in_word)
{
in_word = 1;
count++;
}
else if (*s == c)
in_word = 0;
s++;
}
return (count);
}
static void free_split(char **result, size_t count)
{
while (count > 0)
free(result[--count]);
free(result);
}
static int fill_words(char **res, const char *s, char c)
{
char *word_start;
size_t i;
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
word_start = (char *)s;
while (*s && *s != c)
s++;
res[i] = ft_substr(word_start, 0, s - word_start);
if (!res[i])
{
free_split(res, i);
return (0);
}
i++;
}
}
res[i] = NULL;
return (1);
}
char **ft_split(char const *s, char c)
{
char **result;
if (!s)
return (NULL);
result = (char **)malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!result)
return (NULL);
if (!fill_words(result, s, c))
return (NULL);
return (result);
}
/*
#include <stdio.h>
int main(void)
{
int i = 0;
char **arr = ft_split("a b c", ' ');
if (!arr)
{
printf("Split fail.");
return (1);
}
while (arr[i])
{
printf("%s\n", arr[i]);
free(arr[i]);
i++;
}
free(arr);
return (0);
}*/