-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstr_tok.c
135 lines (123 loc) · 2.57 KB
/
str_tok.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include "shell.h"
/**
* str_tok - breaks a string into tokens using a delimiter specified
* @str: the string
* @delim: the delimeter
* Description: splits up a string by putting '\0' where a delimiter
* character is found and returning the pointer to the start of the
* word that was found. Works exactly like the standard lib strtok
* Return: pointer to the next token/word
*/
char *str_tok(char *str, char *delim)
{
static char *pos;
char *word;
size_t len_delim, i;
if ((str == NULL || *str == 0) && pos == NULL)
return (NULL);
else if (str == NULL && pos != NULL)
str = pos;
else if (str != NULL && pos != NULL)
pos = NULL;
if (delim == NULL || *delim == 0)
return (str);
len_delim = str_len(delim);
while (*str == *delim && *str != 0)
{
if (str_ncmp(str, delim, len_delim) == 0)
{
str += len_delim;
pos = str;
}
else
break;
}
i = 0;
word = str;
while (*(str + i) != *delim && *(str + i) != 0)
{
i++;
if (*(str + i) == *delim)
{
if (str_ncmp(str + i, delim, len_delim) == 0)
{
*(str + i) = '\0';
str += len_delim + i;
pos = str;
break;
}
else
str++;
}
else if (*(str + i) == 0)
{
pos = NULL;
break;
}
}
if (*word == 0)
return (NULL);
else
return (word);
}
/**
* str_tok_r - re-entrant version of str_tok
* @str: the string
* @delim: the delimeter
* @save_ptr: the pointer to the location of the next token
* Description: splits up a string by putting '\0' where a delimiter
* character is found and returning the pointer to the start of the
* word that was found. Works exactly like the standard lib strtok_r
* Return: pointer to the next token/word
*/
char *str_tok_r(char *str, char *delim, char **save_ptr)
{
char *word;
size_t len_delim, i;
if ((str == NULL || *str == 0) && *save_ptr == NULL)
return (NULL);
else if (str == NULL && *save_ptr != NULL)
str = *save_ptr;
else if (str != NULL && *save_ptr != NULL)
*save_ptr = NULL;
if (delim == NULL || *delim == 0)
return (str);
len_delim = str_len(delim);
while (*str == *delim && *str != 0)
{
if (str_ncmp(str, delim, len_delim) == 0)
{
str += len_delim;
*save_ptr = str;
}
else
break;
}
i = 0;
word = str;
while (*(str + i) != *delim && *(str + i) != 0)
{
i++;
if (*(str + i) == *delim)
{
if (str_ncmp(str + i, delim, len_delim) == 0)
{
*(str + i) = '\0';
str += len_delim + i;
*save_ptr = str;
break;
}
else
str++;
}
else if (*(str + i) == 0)
{
*save_ptr = str + i;
break;
}
}
if (*word == 0)
return (NULL);
else
return (word);
}