-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathft_split.c
97 lines (85 loc) · 2.09 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
86
87
88
89
90
91
92
93
94
95
96
97
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tsomsa <tsomsa@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/23 22:51:42 by tsomsa #+# #+# */
/* Updated: 2022/02/23 22:51:44 by tsomsa ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int setlen(char const *s, char c);
static char *setstr(char *dest, char const *src, int len);
static int detlen(char const *s, char c);
static int fitlen(char const *s, char c);
char **ft_split(char const *s, char c)
{
char **arr;
int i;
int j;
int len;
int slen;
slen = ft_strlen(s);
arr = malloc(sizeof(char *) * (fitlen(s, c) + 1));
if (!arr)
return (NULL);
i = 0;
j = detlen(&s[0], c);
while (s[j] && j <= slen)
{
len = setlen(&s[j], c);
arr[i] = malloc(sizeof(char) * len + 1);
if (!arr[i])
return (NULL);
*arr[i] = 0;
arr[i] = setstr(arr[i], &s[j], len);
i++;
j += len + detlen(&s[j + len], c);
}
arr[i] = NULL;
return (arr);
}
static int fitlen(char const *s, char c)
{
int i;
i = 0;
while (*s)
{
if (*s != c)
{
i++;
while (*s != c && *s)
s++;
s--;
}
s++;
}
return (i);
}
static int setlen(char const *s, char c)
{
int i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static int detlen(char const *s, char c)
{
int i;
i = 0;
while (s[i] == c && s[i])
i++;
return (i);
}
static char *setstr(char *dest, char const *src, int len)
{
int i;
i = 0;
while (i < len)
dest[i++] = *src++;
dest[i] = '\0';
return (dest);
}