-
Notifications
You must be signed in to change notification settings - Fork 0
/
lil_libft2.c
111 lines (100 loc) · 2.17 KB
/
lil_libft2.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* lil_libft2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zwalad <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/17 17:49:40 by zwalad #+# #+# */
/* Updated: 2022/03/17 18:23:46 by zwalad ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
char *ps_substr(char *s, unsigned int start, size_t len)
{
char *str;
size_t i;
unsigned int t;
i = 0;
if (!s)
return (NULL);
t = ps_strlen(s);
if (len > t + 1)
len = t + 1;
str = malloc(len + 1);
if (str == NULL)
return (NULL);
while (len > 0 && start + i <= t && s[start + i])
{
str[i] = s[start + i];
i++;
len --;
}
str[i] = '\0';
return (str);
}
static int ps_wnb( char *str, char c)
{
int i;
int j;
i = 0;
j = 0;
while (str[i])
{
if ((str[0] != c && i == 0) || (str[i] != c && str[i - 1] == c))
{
i++;
j++;
}
if (str[i])
i++;
}
return (j);
}
static void ps_free(char **str, int wnbr)
{
int i;
i = 0;
while (i < wnbr)
{
free(str[i]);
i++;
}
}
static void alloc(char **sp, char *s, char c, int wnbr)
{
int i;
int j;
int index;
i = 0;
j = 0;
while (j < wnbr - 1)
{
while (s[i] == c && s[i] != '\0')
i++;
index = i;
while (s[i] != c && s[i] != '\0')
i++;
sp [j] = ps_substr(s, index, i - index);
if (!sp[j])
{
ps_free(sp, j);
break ;
}
j++;
}
sp[j] = NULL;
}
char **ps_split(char *s, char c)
{
char **str;
int wnbr;
if (s == NULL)
return (NULL);
wnbr = ps_wnb(s, c) + 1;
str = malloc(sizeof(char *) * wnbr);
if (str == NULL)
return (NULL);
alloc(str, s, c, wnbr);
return (str);
}