-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
80 lines (72 loc) · 1.8 KB
/
ft_split.c
File metadata and controls
80 lines (72 loc) · 1.8 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amezioun <amezioun@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/27 01:43:18 by amezioun #+# #+# */
/* Updated: 2024/01/11 17:34:45 by amezioun ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count(char const *s, char c)
{
int i;
int wcount;
i = 0;
wcount = 0;
while (s && s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i] != '\0' && s[i] != c)
wcount++;
while (s[i] && s[i] != c)
i++;
}
return (wcount);
}
static int word_len(char const *s, char c, int i)
{
int len;
len = 0;
while (s[i + len] && s[i + len] != c)
len++;
return (len);
}
static void ft_free(char **new, int j)
{
while (j >= 0)
{
free(new[j]);
j--;
}
free(new);
}
char **ft_split(char const *s, char c)
{
int i;
int j;
char **new;
i = 0;
j = 0;
new = (char **)malloc(sizeof(char *) * (count(s, c) + 1));
if (!new)
return (NULL);
while (s && s[i] != '\0' && j < count(s, c))
{
while (s[i] && s[i] == c)
i++;
new[j] = ft_substr(s, i, word_len(s, c, i));
if (!new[j])
{
ft_free(new, j);
return (NULL);
}
i += word_len(s, c, i);
j++;
}
new[j] = NULL;
return (new);
}