-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strsplit.c
More file actions
95 lines (85 loc) · 1.97 KB
/
Copy pathft_strsplit.c
File metadata and controls
95 lines (85 loc) · 1.97 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rtiutiun <rtiutiun@42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/10 20:10:58 by rtiutiun #+# #+# */
/* Updated: 2017/09/25 17:24:35 by rtiutiun ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char *str, int c)
{
int wc;
int skip;
wc = 0;
skip = 1;
while (*str)
{
if (*str == c)
skip = 1;
else if (skip)
{
wc++;
skip = 0;
}
str++;
}
return (wc);
}
static char *next_word(char *str, int c)
{
while (*str == c)
str++;
return (str);
}
static int len_word(char *str, int c)
{
int len;
len = 0;
while ((str[len]) && (str[len] != c))
len++;
return (len);
}
static char *set_word(char **result, char *str, int i, int c)
{
int len;
int j;
j = 0;
str = next_word(str, c);
len = len_word(str, c);
result[i] = (char*)malloc(sizeof(char) * len + 1);
if (!result[i])
return (0);
while (j < len)
{
result[i][j] = str[j];
j++;
}
result[i][j] = '\0';
return (str + len);
}
char **ft_strsplit(char const *s, int c)
{
char **result;
char *str;
int wc;
int i;
if (!s)
return (NULL);
i = 0;
str = (char *)s;
wc = count_words(str, c);
result = (char**)malloc(sizeof(char*) * (wc + 1));
if (!result)
return (NULL);
while (i < wc)
{
str = set_word(result, str, i, c);
i++;
}
result[i] = 0;
return (result);
}