-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
109 lines (98 loc) · 2.39 KB
/
ft_split.c
File metadata and controls
109 lines (98 loc) · 2.39 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
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft2_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lpalacio <lpalacio@student.42madrid> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/26 21:16:36 by lpalacio #+# #+# */
/* Updated: 2022/10/03 22:00:59 by lpalacio ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *trim_substr(char const *s, char c)
{
char *str;
str = (char *)s;
if (c == 0)
return (str);
while (*str != 0 && *str == c)
str++;
return (str);
}
static size_t count_substr(char const *s, char c)
{
char *str;
if (c == 0)
return (2);
str = trim_substr (s, c);
str = ft_strchr(str, c);
if (str == NULL)
return (2);
else
return (count_substr(str, c) + 1);
}
static char **init_matrix(size_t rows, char *str, char c)
{
size_t i;
char **matrix;
matrix = (char **)ft_calloc (rows, sizeof(char *));
if (matrix == NULL)
{
free (str);
return (NULL);
}
matrix [0] = str;
i = 1;
while (i < rows - 1)
{
matrix[i] = ft_strchr(matrix[i - 1], c);
*matrix[i] = 0;
matrix[i] = trim_substr(matrix[i] + 1, c);
i++;
}
return (matrix);
}
static char **assign_matrix(size_t rows, char **matrix)
{
size_t i;
i = 0;
while (i < rows - 1)
{
matrix[i] = ft_substr(matrix[i], 0, ft_strlen(matrix[i]));
if (matrix[i] == NULL)
{
while (--i)
free(matrix[i]);
free (matrix);
return (NULL);
}
i++;
}
matrix[rows - 1] = NULL;
return (matrix);
}
char **ft_split(char const *s, char c)
{
char cs[2];
char *str;
char **matrix;
size_t rows;
cs[0] = c;
cs[1] = 0;
if (s == NULL)
return (NULL);
str = ft_strtrim(s, cs);
if (str == NULL)
return (NULL);
if (*str == 0)
rows = 1;
else
rows = count_substr(str, c);
matrix = init_matrix(rows, str, c);
if (matrix == NULL)
return (NULL);
matrix = assign_matrix(rows, matrix);
free (str);
return (matrix);
}