blob: fbd16c1dc0583d2e6d03ed7c54b757dd488d3f27 (
plain)
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
114
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dkaiser <dkaiser@student.42heilbronn.de +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/08 15:36:44 by dkaiser #+# #+# */
/* Updated: 2024/05/08 11:49:32 by dkaiser ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int get_word_count(char const *s, char c)
{
int word_count;
int cur_len;
word_count = 0;
cur_len = 0;
while (*s)
{
if (!(*s) || *s == c)
{
cur_len = 0;
}
else
{
if (!cur_len)
word_count++;
cur_len++;
}
s++;
}
return (word_count);
}
static char *get_next_token(char const **ptr_s, char c)
{
int i;
int len;
char const *s;
char *result;
s = *ptr_s;
while (*s && *s == c)
s++;
if (!*s)
return (0);
len = 0;
while (s[len] && s[len] != c)
len++;
result = malloc(sizeof(char) * (len + 1));
if (!result)
return (0);
i = 0;
while (i < len)
result[i++] = *(s++);
result[i] = '\0';
*ptr_s = s;
return (result);
}
char **ft_split(char const *s, char c)
{
char **result;
int word_count;
int w;
word_count = get_word_count((char *)s, c);
result = malloc(sizeof(char *) * (word_count + 1));
if (!result)
return (0);
w = 0;
while (w < word_count)
{
result[w] = get_next_token(&s, c);
if (!result[w])
{
while (w--)
free(result[w]);
free(result);
return (0);
}
w++;
}
result[w] = 0;
return (result);
}
void ft_free_split(char **split)
{
int i;
i = 0;
while (split[i])
free(split[i++]);
free(split);
}
/* #include <stdio.h> */
/* int main() */
/* { */
/* char s[] = " split this for me !"; */
/* char **split = ft_split(s, ' '); */
/* if (split) { */
/* while(*split) { */
/* printf("%s\n", *split); */
/* split++; */
/* } */
/* } */
/* } */
|