-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
79 lines (71 loc) · 1.82 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mucankir <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/05 00:44:11 by mucankir #+# #+# */
/* Updated: 2024/11/16 21:06:02 by mucankir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int word_counter(char const *s, char c)
{
int count;
int inword;
inword = 0;
count = 0;
while (*s)
{
if (*s != c && !inword)
{
inword = 1;
count++;
}
else if (*s == c)
inword = 0;
s++;
}
return (count);
}
static int ft_wordlen(char const *s, char c)
{
int len;
len = 0;
while (s[len] != c && s[len])
len++;
return (len);
}
static void free_all(char **split, int i)
{
while (i-- > 0)
free(split[i]);
free(split);
}
char **ft_split(char const *s, char c)
{
int i;
char **split;
int count;
if (!s)
return (NULL);
count = word_counter(s, c);
split = (char **)malloc(sizeof(char *) * (count + 1));
if (!split)
return (NULL);
split[count] = NULL;
i = 0;
while (count-- > 0)
{
while (*s == c)
s++;
if (*s == '\0')
return (split);
split[i] = ft_substr(s, 0, ft_wordlen(s, c));
if (!split[i++])
return (free_all(split, i - 1), NULL);
s += ft_wordlen(s, c);
}
return (split);
}