-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
102 lines (92 loc) · 2.35 KB
/
ft_split.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: figarcia <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/11 16:12:08 by figarcia #+# #+# */
/* Updated: 2024/10/21 18:38:07 by figarcia ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int word_count(char const *s, char c)
{
int count;
int in_word;
count = 0;
in_word = 0;
if (s == NULL)
return (0);
while (*s)
{
if (*s != c && in_word == 0)
{
in_word = 1;
count++;
}
else if (*s == c)
in_word = 0;
s++;
}
return (count);
}
static char *word_dup(const char *s, int start, int end)
{
char *word;
int len;
len = end - start;
if (s == NULL || start < 0 || end <= start)
return (NULL);
word = (char *)malloc(sizeof(char) * (len + 1));
if (word == NULL)
return (NULL);
ft_strlcpy(word, &s[start], len + 1);
return (word);
}
static void free_split(char **result, int word_index)
{
while (word_index >= 0)
{
free(result[word_index]);
word_index--;
}
free(result);
}
static int split_words(char **result, char const *s, char c)
{
int start;
int word_index;
int end;
start = 0;
word_index = 0;
while (s[start] != '\0')
{
while (s[start] == c)
start++;
if (s[start] == '\0')
break ;
end = start;
while (s[end] && s[end] != c)
end++;
result[word_index] = word_dup(s, start, end);
if (!result[word_index])
return (free_split(result, word_index - 1), 0);
word_index++;
start = end;
}
result[word_index] = NULL;
return (1);
}
char **ft_split(char const *s, char c)
{
char **result;
if (s == NULL)
return (NULL);
result = (char **)malloc(sizeof(char *) * (word_count(s, c) + 1));
if (result == NULL)
return (NULL);
if (!split_words(result, s, c))
return (NULL);
return (result);
}