-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
113 lines (102 loc) · 2.25 KB
/
ft_split.c
File metadata and controls
113 lines (102 loc) · 2.25 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: jsmidt <jsmidt@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2025/10/14 14:29:33 by jsmidt #+# #+# */
/* Updated: 2025/10/23 13:05:04 by jsmidt ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
#include <stdlib.h>
size_t ft_strlcpy(char *dst, const char *src, size_t n);
static int checkmalloc(char **arr, int pos, size_t buf)
{
int i;
i = 0;
arr[pos] = malloc(buf);
if (arr[pos] == NULL)
{
while (i < pos)
free(arr[i++]);
free(arr);
return (1);
}
return (0);
}
static int countwords(char const *s, char c)
{
int count;
int inword;
int i;
count = 0;
inword = 0;
i = 0;
while (s[i])
{
if ((s[i] != c) && (inword == 0))
{
inword = 1;
count ++;
}
else if (s[i] == c)
inword = 0;
i++;
}
return (count);
}
static int fill(char **arr, char const *s, char c)
{
int i;
int j;
i = 0;
while (*s)
{
j = 0;
while ((*s == c) && *s)
s++;
while ((*s != c) && *s)
{
j++;
s++;
}
if (j)
{
if (checkmalloc(arr, i, j + 1))
return (1);
ft_strlcpy(arr[i], s - j, j + 1);
i++;
}
}
return (0);
}
char **ft_split(char const *s, char c)
{
char **arr;
int wordcount;
if (s == NULL)
return (NULL);
wordcount = countwords(s, c);
arr = malloc((wordcount + 1) * sizeof(char *));
if (arr == NULL)
return (NULL);
arr[wordcount] = NULL;
if (fill(arr, s, c))
return (NULL);
return (arr);
}
// int main(void)
// {
// int i = 0;
// char *s = "test- en- die ding";
// char c = '-';
// char **res = ft_split(s, c);
// while (res[i])
// {
// printf("%s\n", res[i]);
// i++;
// }
// }