-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
99 lines (88 loc) · 2.32 KB
/
ft_split.c
File metadata and controls
99 lines (88 loc) · 2.32 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dporhomo <dporhomo@student.42prague.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/16 19:03:17 by dporhomo #+# #+# */
/* Updated: 2025/11/24 10:57:25 by dporhomo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_split_words(char const *s, char c, char **arr, int num_words);
static int ft_word_count(char const *s, char c);
static char *ft_word_dup(char const *s, int start, int end);
static void *ft_free_all(char **arr, int i);
char **ft_split(char const *s, char c)
{
char **arr;
int num_words;
if (!s)
return (NULL);
num_words = ft_word_count(s, c);
arr = malloc(sizeof(char *) * (num_words + 1));
if (!arr)
return (NULL);
arr = ft_split_words(s, c, arr, num_words);
return (arr);
}
static int ft_word_count(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
count++;
while (s[i] && s[i] != c)
i++;
}
return (count);
}
static char **ft_split_words(char const *s, char c, char **arr, int num_words)
{
int i;
int w;
int start;
i = 0;
w = 0;
while (w < num_words)
{
while (s[i] && s[i] == c)
i++;
start = i;
while (s[i] && s[i] != c)
i++;
arr[w] = ft_word_dup(s, start, i);
if (!arr[w])
return (ft_free_all(arr, w - 1));
w++;
}
arr[w] = NULL;
return (arr);
}
static char *ft_word_dup(char const *s, int start, int end)
{
char *word;
int j;
word = (char *)malloc(end - start + 1);
if (!word)
return (NULL);
j = 0;
while (start < end)
word[j++] = s[start++];
word[j] = '\0';
return (word);
}
static void *ft_free_all(char **arr, int i)
{
while (i >= 0)
free(arr[i--]);
free(arr);
return (NULL);
}