-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
121 lines (108 loc) · 2.48 KB
/
ft_split.c
File metadata and controls
121 lines (108 loc) · 2.48 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
110
111
112
113
114
115
116
117
118
119
120
121
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: manufern <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/25 16:17:17 by manufern #+# #+# */
/* Updated: 2023/09/30 14:27:06 by manufern ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_string_count(char const *s, char c)
{
int i;
int j;
i = 0;
j = 0;
while (s[i] != '\0')
{
if ((s[i] == c && s[i + 1] != c && s[i + 1] != '\0')
|| (i == 0 && s[i] != c))
{
j ++;
}
i ++;
}
return (j);
}
int ft_word_count(char const *s, char c, int i)
{
int j;
j = 0;
while (s[i] != c && s[i])
{
j ++;
i ++;
}
return (j);
}
char **ft_free(char **aux, int j)
{
while (j > 0)
{
j --;
free ((void *)aux[j]);
}
free(aux);
return (NULL);
}
char **ft_matrix(char **aux, char const *s, char c, int i)
{
int j;
int k;
int l;
j = 0;
while (s[i] != '\0')
{
k = 0;
while (s[i] == c)
i ++;
if (s[i] == '\0')
{
aux[j] = NULL;
return (aux);
}
aux[j] = (char *) malloc((ft_word_count(s, c, i) + 1) * sizeof(char));
if (!aux[j])
return (ft_free(aux, j));
l = ft_word_count(s, c, i);
while (k < l)
aux[j][k ++] = s[i ++];
aux[j ++][k] = '\0';
}
aux[j] = NULL;
return (aux);
}
char **ft_split(char const *s, char c)
{
int words;
char **aux;
words = ft_string_count(s, c);
aux = (char **)malloc((words + 1) * sizeof(char *));
if (!aux)
return (NULL);
aux[words] = NULL;
return (ft_matrix(aux, s, c, 0));
}
/*int main()
{
char const *input_string = "";
char c = '\0';
char **result = ft_split(input_string, c);
if (result)
{
for (int i = 0; result[i] != NULL; i++)
{
printf("Palabra %d: %s\n", i + 1, result[i]);
}
// Liberar la memoria asignada dinámicamente
free(result);
}
else
{
printf("Error al dividir la cadena.\n");
}
return (0);
}*/