-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_split.c
111 lines (101 loc) · 1.65 KB
/
my_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
#include "libft.h"
static int count_words(char const *s, char c)
{
int i;
int count;
i = 0;
if (!s)
return (0);
if (s[0] == c)
count = 0;
else if (c == '\0')
{
count = 1;
return (count);
}
else
count = 1;
while (s[i])
{
if ((s[i] == c) && (s[i + 1] != '\0') && (s[i + 1] != c))
count++;
i++;
}
return (count);
}
static char *new_str(char const *s, int start, int end)
{
int j;
char *str;
j = 0;
if (!s)
return (0);
str = (char *)my_calloc((end - start + 2), sizeof(char));
if (!str)
return (NULL);
while (start <= end)
{
str[j] = s[start];
start++;
j++;
}
str[j] = '\0';
return (str);
}
static int verification(char const *s, char c, char **vect)
{
int j;
j = 0;
if (!vect || !s)
return (0);
if (s[0] == '\0')
{
vect[j] = NULL;
return (1);
}
if (c == '\0')
{
vect[j] = new_str(s, 0, my_strlen(s));
vect[j + 1] = NULL;
return (1);
}
return (2);
}
static char **make_vect(char const *s, char c, char **vect, int count)
{
size_t i;
int j;
int start;
j = 0;
i = 0;
start = 0;
while (j < count)
{
if (s[i] != c && i >= 1 && s[i - 1] == c)
start = i;
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
{
vect[j] = new_str(s, start, i);
if (!vect[j])
return (my_clear_vect(vect, j));
j++;
}
if ((i - 1) == my_strlen(s))
break ;
i++;
}
vect[j] = NULL;
return (vect);
}
char **my_split(char const *s, char c)
{
int count;
char **vect;
count = count_words(s, c);
vect = (char **)my_calloc((count + 1), sizeof(char *));
if (verification(s, c, vect) == 0)
return (NULL);
if (verification(s, c, vect) == 1)
return (vect);
return (make_vect(s, c, vect, count));
}