-
Notifications
You must be signed in to change notification settings - Fork 8
/
split.c
executable file
·104 lines (87 loc) · 1.97 KB
/
split.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
#include "shell.h"
int token_len(char *str, char *delim);
int count_tokens(char *str, char *delim);
char **_strtok(char *line, char *delim);
/**
* token_len - Locates the delimiter index marking the end
* of the first token contained within a string.
* @str: The string to be searched.
* @delim: The delimiter character.
*
* Return: The delimiter index marking the end of
* the intitial token pointed to be str.
*/
int token_len(char *str, char *delim)
{
int index = 0, len = 0;
while (*(str + index) && *(str + index) != *delim)
{
len++;
index++;
}
return (len);
}
/**
* count_tokens - Counts the number of delimited
* words contained within a string.
* @str: The string to be searched.
* @delim: The delimiter character.
*
* Return: The number of words contained within str.
*/
int count_tokens(char *str, char *delim)
{
int index, tokens = 0, len = 0;
for (index = 0; *(str + index); index++)
len++;
for (index = 0; index < len; index++)
{
if (*(str + index) != *delim)
{
tokens++;
index += token_len(str + index, delim);
}
}
return (tokens);
}
/**
* _strtok - Tokenizes a string.
* @line: The string.
* @delim: The delimiter character to tokenize the string by.
*
* Return: A pointer to an array containing the tokenized words.
*/
char **_strtok(char *line, char *delim)
{
char **ptr;
int index = 0, tokens, t, letters, l;
tokens = count_tokens(line, delim);
if (tokens == 0)
return (NULL);
ptr = malloc(sizeof(char *) * (tokens + 2));
if (!ptr)
return (NULL);
for (t = 0; t < tokens; t++)
{
while (line[index] == *delim)
index++;
letters = token_len(line + index, delim);
ptr[t] = malloc(sizeof(char) * (letters + 1));
if (!ptr[t])
{
for (index -= 1; index >= 0; index--)
free(ptr[index]);
free(ptr);
return (NULL);
}
for (l = 0; l < letters; l++)
{
ptr[t][l] = line[index];
index++;
}
ptr[t][l] = '\0';
}
ptr[t] = NULL;
ptr[t + 1] = NULL;
return (ptr);
}