Repository navigation
Expand file tree
/
Copy pathsplit.c
More file actions
98 lines (88 loc) · 1.41 KB
/
Copy pathsplit.c
File metadata and controls
98 lines (88 loc) · 1.41 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
#include "shell.h"
char *substr(char *s, unsigned int start, size_t len)
{
char *sub;
size_t length;
size_t i;
length = _strlen(s);
i = 0;
if (s)
{
if (start > length)
length = 0;
if (len > length && len)
len = length;
if (length <= start + len && len)
len = length - start;
sub = (char *)malloc((len + 1) * sizeof(char));
if (sub)
{
while (i < len)
sub[i++] = s[start++];
sub[i] = '\0';
}
return (sub);
}
return (NULL);
}
static void _free(char **matrice, int last)
{
int i;
i = 0;
while (i < last)
free(matrice[i++]);
free(matrice);
matrice = (NULL);
}
static int _strdlen(const char *s, char d)
{
int i;
i = 0;
while (*(s + i) != d && *(s + i))
i++;
return (i);
}
static int _wordcount(const char *s, char c)
{
int count;
int len;
count = 0;
while (*s)
{
while (*s == c && *s)
s++;
len = _strdlen(s, c);
if (len)
{
count++;
s += len;
}
}
return (count);
}
char **split(char *s, char c)
{
t_split sp;
sp.count = _wordcount(s, c);
sp.matrice = (char **)malloc((sp.count + 1) * sizeof(char *));
if (sp.matrice)
{
sp.i = 0;
while (sp.i < sp.count)
{
if (*s != c && *s)
{
sp.j = _strdlen(s, c);
*(sp.matrice + sp.i) = substr(s, 0, sp.j);
if (!*(sp.matrice + sp.i))
return (_free(sp.matrice, sp.i), NULL);
s = s + sp.j;
sp.i++;
}
else
s++;
}
*(sp.matrice + sp.i) = NULL;
}
return (sp.matrice);
}