-
Notifications
You must be signed in to change notification settings - Fork 0
/
split.c
92 lines (81 loc) · 2.04 KB
/
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abertran <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/07 19:05:59 by abertran #+# #+# */
/* Updated: 2023/03/08 20:31:56 by abertran ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
static unsigned int countwords(const char *s, char c)
{
unsigned int count;
count = 0;
while (*s)
{
while (*s && c == *s)
s++;
if (*s)
count++;
while (*s && *s != c)
s++;
}
return (count);
}
static char *word_dup(const char *str, int start, int finish)
{
char *word;
int i;
i = 0;
word = malloc((finish - start + 1) * sizeof(char));
if (!word)
return (NULL);
while (start < finish)
word[i++] = str[start++];
word[i] = '\0';
return (word);
}
static char *ft_cpy(size_t i, char const *s, char c, char **split)
{
int index;
size_t j;
index = -1;
j = 0;
while (i <= ft_strlen(s))
{
if (s[i] != c && index < 0)
index = i;
else if ((s[i] == c || i == ft_strlen(s)) && index >= 0)
{
split[j++] = word_dup(s, index, i);
index = -1;
}
i++;
}
split[j] = 0;
return (split[j]);
}
char **ft_split(char const *s, char c)
{
size_t i;
char **split;
if (!s)
return (NULL);
split = malloc((countwords(s, c) + 1) * sizeof(char *));
if (!split)
return (NULL);
i = 0;
ft_cpy(i, s, c, split);
return (split);
}