Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
106 lines (95 loc) · 2.31 KB
/
Copy pathft_split.c
File metadata and controls
106 lines (95 loc) · 2.31 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dchernyk <dchernyk@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/21 17:16:11 by dchernyk #+# #+# */
/* Updated: 2026/04/27 13:15:58 by dchernyk ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static unsigned int count_words(char const *s, char c)
{
unsigned int in_word;
unsigned int counter;
counter = 0;
in_word = 0;
while (*s)
{
if (in_word == 0 && !(*s == c))
{
in_word = 1;
counter++;
}
else if (in_word == 1 && *s == c)
in_word = 0;
s++;
}
return (counter);
}
static void free_logic(char **outer, unsigned int j)
{
while (j > 0)
{
j--;
free(outer[j]);
}
free(outer);
}
static int split_logic(char **outer, unsigned int words, char const *s, char c)
{
unsigned int i;
unsigned int j;
unsigned int start;
unsigned int len;
char *inner;
i = 0;
j = 0;
while (j < words)
{
while (s[i] == c && s[i])
i++;
start = i;
while (s[i] != c && s[i])
i++;
len = i - start;
inner = malloc((len + 1) * sizeof(char));
if (!inner)
return (free_logic(outer, j), 0);
ft_strlcpy(inner, &s[start], len + 1);
outer[j++] = inner;
}
outer[j] = NULL;
return (1);
}
char **ft_split(char const *s, char c)
{
unsigned int words;
char **outer;
if (!s)
return (NULL);
words = count_words(s, c);
outer = malloc((words + 1) * sizeof(char *));
if (!outer)
return (NULL);
if (split_logic(outer, words, s, c) == 0)
return (NULL);
return (outer);
}
/*#include <stdio.h>
int main(void)
{
char test[] = " Adfd dsfdsfs rtert ";
char **result = ft_split(test, ' ');
int i;
if (!result)
return (1);
i = 0;
while (result[i])
{
printf("%s\n", result[i]);
i++;
}
}*/