-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
74 lines (67 loc) · 1.74 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yrigny <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/13 12:09:51 by yrigny #+# #+# */
/* Updated: 2023/11/13 15:05:15 by yrigny ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int countwords(char const *s, char c)
{
int count;
count = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
count += 1;
while (*s && *s != c)
s++;
}
return (count);
}
char **copywords(int wordcount, char **dest, char const *s, char c)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (s[j] && i < wordcount)
{
while (s[j] == c)
j++;
start = j;
while (s[j] && s[j] != c)
j++;
dest[i] = ft_substr(s, start, j - start);
if (!dest[i])
{
while (i-- >= 0)
free(dest[i]);
free(dest);
return (NULL);
}
i++;
}
dest[i] = 0;
return (dest);
}
char **ft_split(char const *s, char c)
{
int wordcount;
char **dest;
if (s == NULL)
return (NULL);
wordcount = countwords(s, c);
dest = malloc(sizeof(char *) * (wordcount + 1));
if (!dest)
return (NULL);
dest = copywords(wordcount, dest, s, c);
return (dest);
}