-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
92 lines (84 loc) · 2.05 KB
/
ft_split.c
File metadata and controls
92 lines (84 loc) · 2.05 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bhielsch <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/13 17:16:55 by bhielsch #+# #+# */
/* Updated: 2022/10/13 17:52:41 by bhielsch ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
static int words_count(const char *str, char c)
{
int i;
int count;
count = 0;
i = 0;
while (str[i])
{
if (str[i] != c)
{
while (str[i] && str[i] != c)
i++;
count++;
}
else
i++;
}
return (count);
}
static char *word_cpy(const char *str, int start, int end)
{
char *word;
int i;
i = 0;
word = (char *)malloc(end - start + 1);
while (start < end)
{
word[i] = str[start];
i++;
start++;
}
word[i] = '\0';
return (word);
}
char **ft_split(char const *s, char c)
{
size_t i;
size_t j;
int k;
char **str;
str = malloc(sizeof(char *) * (words_count(s, c) + 1));
if (!str || !s)
return (0);
i = 0;
j = 0;
k = -1;
while (i <= ft_strlen(s))
{
if (s[i] != c && k < 0)
k = i;
else if ((s[i] == c || i == ft_strlen(s)) && k >= 0)
{
str[j++] = word_cpy(s, k, i);
k = -1;
}
i++;
}
str[j] = 0;
return (str);
}
// int main(void)
// {
// char *s = "split ||this|for|me|||||!|";
// char **tab = ft_split(s, '|');
// for (int i = 0; tab[i]; i++)
// {
// if (tab[i] != ((void*)0))
// printf("Fail");
// }
// printf("Sucess");
// }