-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
executable file
·94 lines (84 loc) · 2 KB
/
ft_split.c
File metadata and controls
executable file
·94 lines (84 loc) · 2 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gyong-si <gyongsi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/15 16:23:30 by gyong-si #+# #+# */
/* Updated: 2023/09/23 22:42:18 by gyong-si ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (s[i])
{
if (s[i] != c)
{
count++;
while (s[i] && s[i] != c)
i++;
}
else if (s[i] == c)
i++;
}
return (count);
}
static size_t get_word_len(char const *s, char c)
{
size_t i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static void free_array(size_t i, char **array)
{
while (i > 0)
{
i--;
free(array[i]);
}
free(array);
}
static char **split(char const *s, char c, char **array, size_t words_count)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (i < words_count)
{
while (s[j] && s[j] == c)
j++;
array [i] = ft_substr(s, j, get_word_len(&s[j], c));
if (!array[i])
{
free_array(i, array);
return (NULL);
}
while (s[j] && s[j] != c)
j++;
i++;
}
array[i] = NULL;
return (array);
}
char **ft_split(char const *s, char c)
{
char **array;
size_t words;
if (!s)
return (NULL);
words = count_words(s, c);
array = (char **)malloc(sizeof(char *) * (words + 1));
if (!array)
return (NULL);
array = split(s, c, array, words);
return (array);
}