-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
81 lines (73 loc) · 1.89 KB
/
Copy pathft_split.c
File metadata and controls
81 lines (73 loc) · 1.89 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rbetz <rbetz@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/07 14:19:54 by rbetz #+# #+# */
/* Updated: 2022/07/18 15:15:55 by rbetz ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_free_arr(char **ptr, int words)
{
words++;
while (ptr[words] != NULL)
{
free(ptr[words]);
words++;
}
free(ptr);
return (NULL);
}
static char *ft_copy(const char *s, int i, int j)
{
char *p;
p = ft_calloc(j + 1, 1);
if (p == NULL)
return (NULL);
ft_memcpy(p, &s[i - j + 1], j);
return (p);
}
int ft_wordcount(char const *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i] != '\0')
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
words++;
i++;
}
return (words);
}
char **ft_split(char const *s, char c)
{
char **ptr;
int i;
int j;
int words;
if (s == NULL)
return (NULL);
words = ft_wordcount(s, c);
ptr = ft_calloc(words + 1, sizeof(char *));
i = ft_strlen(s) - 1;
while (i >= 0 && words > 0 && ptr != NULL)
{
if (s[i] != c)
{
j = 1;
while (j <= i && s[i - j] != c)
j++;
ptr[--words] = ft_copy(s, i, j);
if (ptr[words] == NULL)
return (ft_free_arr(ptr, words));
i = i - j + 1;
}
i--;
}
return (ptr);
}