-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
117 lines (105 loc) · 2.23 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
114
115
116
117
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ivan-mel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/19 11:49:03 by ivan-mel #+# #+# */
/* Updated: 2023/05/22 18:19:03 by ivan-mel ### ########.fr */
/* */
/* ************************************************************************** */
#include <string.h>
#include <stdlib.h>
#include "libft.h"
int ft_wordcount(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
if (s[i] != c)
count++;
while (s[i] != '\0' && s[i] != c)
{
i++;
}
if (s[i] == '\0')
return (count);
i++;
}
return (count);
}
int ft_wordlength(char const *s, char c)
{
int i;
i = 0;
while (s[i] != '\0' && s[i] != c)
{
if (s[i] == c)
break ;
i++;
}
return (i);
}
void ft_free(char **array)
{
int i;
i = 0;
while (array[i] != NULL)
{
free(array[i]);
i++;
}
free (array);
return ;
}
void ft_loopsplit(char const *s, char **array, char c)
{
int i;
int index;
i = 0;
index = 0;
while (s[i] != '\0')
{
if (s[i] != '\0' && s[i] != c)
{
array[index] = ft_substr(s, i, ft_wordlength(s + i, c));
if (!array[index])
{
ft_free(array);
}
index++;
i = i + ft_wordlength(s + i, c);
if (s[i] == '\0')
break ;
}
i++;
}
}
char **ft_split(char const *s, char c)
{
char **array;
if (!s)
return (NULL);
array = ft_calloc(sizeof(char *), (ft_wordcount(s, c) + 1));
if (!array)
return (NULL);
ft_loopsplit(s, array, c);
return (array);
}
/*
int main(void)
{
const char *str = " hi";
char b = 32;
char **array = ft_split(str, b);
int i = 0;
while (array[i]) {
printf("word %i: %s\n", i, array[i]);
i++;
}
return (0);
}*/