-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
97 lines (86 loc) · 2.14 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: sutku <sutku@student.42heilbronn.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/22 05:38:49 by sutku #+# #+# */
/* Updated: 2022/10/24 03:51:12 by sutku ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int word_len(char const *s, unsigned int i, char c)
{
int word;
word = 0;
while (s[i + word] != '\0' && s[i + word] != c)
word++;
return (word);
}
static unsigned int word_counter(char const *s, char c)
{
unsigned int counter;
unsigned int i;
i = 0;
counter = 0;
while (s[i] != '\0')
{
while (s[i] == c)
i++;
if (s[i] != '\0')
counter++;
while (s[i] != c && s[i] != '\0')
i++;
}
return (counter);
}
void sub_writer(char const *s, unsigned int i, char *ptr, char c)
{
unsigned int j;
j = 0;
while (j < word_len(s, i, c))
{
ptr[j] = s[i + j];
j++;
}
ptr[j] = '\0';
}
void *memory_free(char **ptr, unsigned int i)
{
unsigned int j;
j = 0;
while (j < i)
{
free(ptr[j]);
j++;
}
free(ptr);
return (NULL);
}
char **ft_split(char const *s, char c)
{
unsigned int i;
unsigned int j;
char **arr;
if (!s)
return (NULL);
arr = (char **)malloc((word_counter(s, c) + 1) * sizeof(char *));
if (!arr)
return (NULL);
i = 0;
j = 0;
while (i < word_counter(s, c))
{
while (s[j] == c)
j++;
arr[i] = (char *)malloc((word_len(s, j, c) + 1) * sizeof(char));
if (!arr[i])
return (memory_free(arr, i));
sub_writer(s, j, arr[i], c);
j += word_len(s, j, c);
i++;
}
arr[i] = NULL;
return (arr);
}