-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strsplit2.c
More file actions
81 lines (72 loc) · 2.07 KB
/
Copy pathft_strsplit2.c
File metadata and controls
81 lines (72 loc) · 2.07 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mhorn <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/30 13:39:04 by mhorn #+# #+# */
/* Updated: 2016/11/30 16:11:58 by mhorn ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
/*
** ft_strsplit2 doesn't trim off the separating characters
** word_count returns the number of splitting chars
** next_word separates strings by the split char and can have strings with
** just the split char as the value
*/
static int word_count(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
if (s[i] == c || s[i + 1] == '\0')
count++;
i++;
}
return (count);
}
/*
** j is the start position of the sub-string
** i - j + 1 is the end position of the sub-string, it includes the split char
*/
static char *next_word(int *i, char const *s, char c)
{
int j;
if (!s)
return (NULL);
j = (*i != 0) ? ++*i : *i;
while (s[*i] != c && s[*i] != '\0')
++*i;
return (ft_strsub(s, (unsigned int)j, (size_t)(*i - j + 1)));
}
char **ft_strsplit2(char const *s, char c)
{
char **arr;
int *i;
int j;
int word_ct;
if (!s)
return (NULL);
i = malloc(sizeof(int) * 1);
word_ct = word_count(s, c);
if (!i)
return (NULL);
*i = 0;
j = 0;
arr = (char **)malloc(sizeof(char *) * (word_ct + 1));
if (arr != NULL)
{
while (s[*i] != '\0' && j < word_ct)
{
arr[j] = next_word(i, s, c);
j++;
}
arr[j] = NULL;
}
return (arr);
}