-
Notifications
You must be signed in to change notification settings - Fork 1
/
strtok.c
52 lines (42 loc) · 1.19 KB
/
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
#include "unixshell.h"
/**
* _strtok- a function to tokenize a string into smaller substrings
* @str: the string to be parsed
*@delim: apointert to NULL terminated characters to split delimiting character
*@saveptr: a pointer to a char * variable that is used in order to
* maintain context between successive calls that parse the same string
*
* Return: A pointer to nexte element
*
**/
char *_strtok(char *str, const char *delim, char **saveptr)
{
char *token_start;
char *token_end;
if (str != NULL)
*saveptr = str;
else if (*saveptr == NULL || **saveptr == '\0')
return (NULL); /* No more tokens to tokenize */
/* Find the start of the token */
token_start = *saveptr;
while (*token_start != '\0' && _strchr(delim, *token_start) != NULL)
token_start++;
if (*token_start == '\0')
{
*saveptr = NULL; /* There is no more tokens to tokenize */
return (NULL);
}
/* Find the end of the token*/
token_end = token_start;
while (*token_end != '\0' && _strchr(delim, *token_end) == NULL)
token_end++;
/* Null-terminate the token and update saveptr */
if (*token_end != '\0')
{
*token_end = '\0';
*saveptr = token_end + 1;
}
else
*saveptr = NULL;
return (token_start);
}