-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
114 lines (104 loc) · 2.44 KB
/
Copy pathft_split.c
File metadata and controls
114 lines (104 loc) · 2.44 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
105
106
107
108
109
110
111
112
113
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kinamura <kinamura@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/18 23:39:24 by kinamura #+# #+# */
/* Updated: 2024/04/30 02:36:52 by kinamura ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void contents_free(char **result, size_t count)
{
while (count > 0)
{
count--;
free(result[count]);
}
free(result);
}
static int count_words(char const *str, char c)
{
int count;
int flag;
size_t index;
if (!str)
return (0);
index = 0;
count = 0;
flag = 0;
while (str[index])
{
if (str[index] != c && flag == 0)
{
flag = 1;
count++;
}
else if (str[index] == c)
flag = 0;
index++;
}
return (count);
}
static char *ft_strndup(const char *str, size_t len)
{
char *word;
size_t index;
if (!len)
return (NULL);
word = (char *)malloc(sizeof(char) * (len + 1));
if (!word)
return (NULL);
index = 0;
while (str[index] && index < len)
{
word[index] = str[index];
index++;
}
word[len] = '\0';
return (word);
}
static char **ft_separate(const char *s, char c, char **result, size_t *count)
{
size_t index;
size_t start;
index = 0;
while (s[index])
{
while (s[index] && s[index] == c)
index++;
start = index;
while (s[index] && s[index] != c)
index++;
if (index > start)
{
result[*count] = ft_strndup(s + start, index - start);
if (!result[*count])
{
contents_free(result, *count);
return (NULL);
}
(*count)++;
}
}
return (result);
}
char **ft_split(char const *s, char c)
{
int words;
char **result;
size_t count;
if (!s)
return (NULL);
words = count_words(s, c);
result = (char **)malloc(sizeof(char *) * (words + 1));
if (!result)
return (NULL);
count = 0;
if (!ft_separate(s, c, result, &count))
return (NULL);
result[count] = NULL;
return (result);
}