-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
84 lines (77 loc) · 1.83 KB
/
Copy pathft_split.c
File metadata and controls
84 lines (77 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsyvasal <bsyvasal@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/26 10:54:47 by bsyvasal #+# #+# */
/* Updated: 2023/11/08 10:35:26 by bsyvasal ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int i;
int wordscount;
int foundword;
i = 0;
wordscount = 0;
while (s[i])
{
foundword = 0;
while (s[i] == c && s[i])
i++;
while (s[i] != c && s[i])
{
i++;
foundword = 1;
}
if (foundword)
wordscount++;
}
return (wordscount);
}
static int arrayaddword(char **strarr, char const *s, int j, int i)
{
char *str;
str = ft_substr(s, 0, i);
if (!str)
{
while (--j >= 0)
{
free(strarr[j]);
}
free(strarr);
return (0);
}
strarr[j] = str;
return (1);
}
char **ft_split(char const *s, char c)
{
char **strarr;
int i;
int j;
if (!s)
return (0);
strarr = malloc((count_words(s, c) + 1) * sizeof (char *));
if (!strarr)
return (0);
i = 0;
j = 0;
while (s[i])
{
while (s[i] && s[i] != c)
i++;
if (i)
if (!arrayaddword(strarr, s, j++, i))
return (0);
while (s[i] == c && s[i])
i++;
s += i;
i = 0;
}
strarr[j] = 0;
return (strarr);
}