-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
113 lines (104 loc) · 2.42 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fvon-nag <fvon-nag@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/12/16 10:55:55 by fvon-nag #+# #+# */
/* Updated: 2023/01/05 13:33:30 by fvon-nag ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int splitcount(char const *s, char c, int *countnc)
{
int i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
if ((i == 0 || s[i - 1] == c) && s[i] != c)
count++;
else if (s[i] != c && s[i + 1] != c)
(*countnc)++;
i++;
}
return (count);
}
static void lengthcount(char const *s, char c, int *lenlist)
{
int i;
int countnc;
int y;
int slength;
slength = ft_strlen(s);
y = 0;
i = 0;
countnc = 0;
while (s[i] != '\0')
{
if (s[i] != c)
countnc++;
if ((i > 0 && (s[i] == c || i == slength - 1) && s[i - 1] != c))
{
lenlist[y] = countnc;
y++;
countnc = 0;
}
i++;
}
}
static char **transfer(char const *s, char c, char **out)
{
int i;
int j;
int y;
i = 0;
j = 0;
y = 0;
while (s[i] != '\0')
{
while (s[i] != '\0' && s[i] != c)
{
out[y][j] = s[i];
i++;
j++;
}
while (s[i] != '\0' && s[i] == c && i > 0 && s[i - 1] != c)
{
j = 0;
y++;
i++;
}
while ((s[i] == c && i == 0) || (s[i] == c && s[i - 1] == c))
i++;
}
return (out);
}
char **ft_split(char const *s, char c)
{
int y;
int count;
char **out;
int *lenlist;
int countnc;
countnc = 0;
count = splitcount(s, c, &countnc);
if (count == 0 && countnc > 0)
count = 1;
out = (char **) ft_calloc((count + 1), sizeof(char *));
if (out == NULL)
return (NULL);
lenlist = malloc((count) * sizeof(int));
lengthcount(s, c, lenlist);
y = 0;
while (y < count)
{
out[y] = (char *) ft_calloc(lenlist[y] + 1, sizeof(char));
y++;
}
free(lenlist);
return (transfer(s, c, out));
}