-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
85 lines (76 loc) · 1.92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahmaymou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/09 10:30:40 by ahmaymou #+# #+# */
/* Updated: 2022/11/12 14:50:31 by ahmaymou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **free_all(char **str)
{
int i;
i = 0;
while (str[i])
{
free(str[i]);
i++;
}
free(str);
return (NULL);
}
static int count_words(const char *str, char charset)
{
int i;
int count;
count = 0;
i = 0;
while (str[i] != '\0')
{
while (str[i] != '\0' && str[i] == charset)
i++;
if (str[i] != '\0')
count++;
while (str[i] != '\0' && str[i] != charset)
i++;
}
return (count);
}
static int word_length(const char *str, char charset)
{
int i;
i = 0;
while (str[i] && str[i] != charset)
i++;
return (i);
}
char **ft_split(const char *str, char c)
{
char **strings;
int i;
i = 0;
if (!str)
return (NULL);
strings = (char **)malloc(sizeof(char *) * (count_words(str, c) + 1));
if (!strings)
return (NULL);
while (*str != '\0')
{
while (*str != '\0' && *str == c)
str++;
if (*str != '\0')
{
strings[i] = ft_substr(str, 0, word_length(str, c));
if (!strings[i])
return (free_all(strings));
i++;
}
while (*str && *str != c)
str++;
}
strings[i] = 0;
return (strings);
}