-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenize.c
83 lines (71 loc) · 1.53 KB
/
tokenize.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
#include "shell.h"
/**
* tokenize - create an argument vector from a delimited string
* @str: string to work on
* @delim: a set of bytes that delimit the string
* Description: space and newline delimited entries
* Return: the argument vector else, NULL on error
*/
char **tokenize(char *str, const char *delim)
{
char **toks = NULL, *tmp = NULL;
char *DELIM = " \n";
bool incomplete = false;
size_t i = 0, tok_count = 0;
if (str == NULL)
{
return (NULL);
}
DELIM = (delim == NULL) ? DELIM : (char *)delim;
tok_count = count_tok(str, DELIM);
toks = malloc((tok_count + 1) * sizeof(char *));
/* extra for the ending NULL argument */
if (toks == NULL)
{
return (NULL);
}
for (i = 0, tmp = str; i < tok_count; i++, tmp = NULL)
{
toks[i] = strtok(tmp, DELIM);
if (toks[i] == NULL && i < tok_count)
{
incomplete = true;
break;
}
}
if (incomplete == true)
{
toks = realloc(toks, (i + 1) * sizeof(char *));
if (toks == NULL)
return (NULL);
}
toks[i] = NULL; /* terminate the vector */
return (toks);
}
/**
* count_tok - count the number of tokens in a string
* @str: to search
* @delim: a string of delimiters to look out for
*
* Return: the number of tokens found, else -1 on error
*/
int count_tok(const char *str, const char *delim)
{
size_t i = 0, count = 0;
if (str == NULL || delim == NULL)
{
return (-1);
}
for (i = 0; str[i];)
{
if (!strchr(delim, str[i]))
{/* token found */
for (; str[i] && !strchr(delim, str[i]); i++)
;
count++;
}
else
i++;
}
return (count);
}