-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_strtok.c
More file actions
117 lines (99 loc) · 1.98 KB
/
_strtok.c
File metadata and controls
117 lines (99 loc) · 1.98 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include "shell.h"
/**
* token_length - returns token's length
* @input: a token
* @position: index position
* @delim: delimiter
* Return: token length
*/
int token_length(char *input, int position, char delim)
{
int length = 0;
while ((input[position] != delim) && (input[position] != '\0'))
{
position++;
length++;
}
return (length);
}
/**
* count_delim - returns number of delimiters
* @input: user's command
* @delim: delimiter
* Return: number of delimiters
*/
int count_delim(char *input, char delim)
{
int index = 0, num_delim = 0;
while (input[index] != '\0')
{
if ((input[index] == delim) && (input[index + 1] != delim))
{
num_delim++;
}
if ((input[index] == delim) && (input[index + 1] == '\0'))
{
num_delim--;
}
index++;
}
return (num_delim);
}
/**
* ignore_delim - returns string without delims
* @str: string
* @delim: delimiter
* Return: new string
*/
char *ignore_delim(char *str, char delim)
{
while (*str == delim)
{
str++;
}
return (str);
}
/**
* _strtok - breaks string str into a series of tokens
* @str: string
* @delim: delimiters
* Return: pointer
*/
char **_strtok(char *str, char *delim)
{
int bufsize = 0, pos = 0, si = 0, index = 0, len = 0, se = 0, t = 0;
char **toks = NULL, delim_ch;
delim_ch = delim[0];
str = ignore_delim(str, delim_ch);
bufsize = count_delim(str, delim_ch);
toks = malloc(sizeof(char *) * (bufsize + 2));
if (toks == NULL)
return (NULL);
while (str[se] != '\0')
se++;
while (si < se)
{
if (str[si] != delim_ch)
{
len = token_length(str, si, delim_ch);
toks[pos] = malloc(sizeof(char) * (len + 1));
if (toks[pos] == NULL)
return (NULL);
index = 0;
while ((str[si] != delim_ch) && (str[si] != '\0'))
{
toks[pos][index] = str[si];
index++;
si++;
}
toks[pos][index] = '\0';
t++;
}
if (si < se && (str[si + 1] != delim_ch && str[si + 1] != '\0'))
pos++;
si++;
}
pos++;
toks[pos] = NULL;
return (toks);
}