-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_splitbyspace.c
88 lines (78 loc) · 1.35 KB
/
ft_splitbyspace.c
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
#include "libft.h"
static int word_count(char *str)
{
int i;
int count;
i = 0;
count = 0;
while (str[i])
{
while (str[i] && (str[i] == ' ' || str[i] == '\t' || str[i] == '\n'))
i ++;
if (str[i])
count ++;
while (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '\n'))
i++;
}
return (count);
}
static char *ft_copy_string(char *dest, char *src, int len)
{
int i;
i = 0;
while (i < len)
{
dest[i] = src[i];
i ++;
}
dest[i] = '\0';
return (dest);
}
static void *ft_free_arr(char **arr)
{
int i;
i = 0;
while (arr[i])
{
free(arr[i]);
arr[i] = NULL;
i ++;
}
free(arr);
arr = NULL;
return (NULL);
}
static char **intermediate(char *str, char **arr, int start, int k)
{
int i;
i = 0;
while (str[i])
{
while (str[i] && (str[i] == ' ' || str[i] == '\t' || str[i] == '\n'))
i++;
start = i;
while (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '\n'))
i++;
if (i > start)
{
arr[k] = (char *)malloc(sizeof(char) * ((i - start) + 1));
if (!arr[k])
return (ft_free_arr(arr));
ft_copy_string(arr[k], &str[start], i - start);
k ++;
}
}
arr[k] = NULL;
return (arr);
}
char **ft_splitbyspace(char *str)
{
char **arr;
arr = malloc(sizeof(char *) * (word_count(str) + 1));
if (!arr)
return (NULL);
arr = intermediate(str, arr, 0, 0);
if (!arr)
return (NULL);
return (arr);
}