-
Notifications
You must be signed in to change notification settings - Fork 0
/
c_strtok.c
70 lines (64 loc) · 1.56 KB
/
c_strtok.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
#include "shell.h"
/**
* c_t_size - returns number of delim
* @str: user's command typed into shell
* @delm: delimeter (e.g. " ");
* Return: number of tokens
*/
int c_t_size(char *str, char delm)
{
int i = 0, num_delm = 0;
while (str[i] != '\0')
{
if (str[i] == delm)
{
num_delm++;
}
i++;
}
return (num_delm);
}
/**
* c_str_tok - tokenizes a string even the continuous delim with empty string
* (e.g. path --> ":/bin::/bin/usr" )
* @str: user's command typed into shell
* @delm: delimeter (e.g. " ");
* Return: an array of tokens (e.g. {"\0", "/bin", "\0", "/bin/usr"}
* (purpose is to have which command look through current directory if ":")
*/
char **c_str_tok(char *str, char *delm)
{
int buffsize = 0, p = 0, si = 0, i = 0, len = 0, se = 0;
char **toks = NULL, d_ch;
/* set variable to be delimeter character (" ") */
d_ch = delm[0];
/* malloc number of ptrs to store array of tokens, and NULL ptr */
buffsize = c_t_size(str, d_ch);
toks = malloc(sizeof(char *) * (buffsize + 2));
if (toks == NULL)
return (NULL);
/* iterate from string index 0 to string ending index */
while (str[se] != '\0')
se++;
while (si < se)
{
/* malloc lengths for each token ptr in array */
len = t_strlen(str, si, d_ch);
toks[p] = malloc(sizeof(char) * (len + 1));
if (toks[p] == NULL)
return (NULL);
i = 0;
while ((str[si] != d_ch) &&
(str[si] != '\0'))
{
toks[p][i] = str[si];
i++;
si++;
}
toks[p][i] = '\0'; /* null terminate at end*/
p++;
si++;
}
toks[p] = NULL; /* set last array ptr to NULL */
return (toks);
}