-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstring_lib_2.c
More file actions
133 lines (121 loc) · 2.17 KB
/
Copy pathstring_lib_2.c
File metadata and controls
133 lines (121 loc) · 2.17 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "hsh.h"
/**
* free_str_array - free a string array
* @str_array: string array to free
* Return: void
*/
void free_str_array(char **str_array)
{
int i = 0;
if (str_array == NULL)
return;
for (i = 0; str_array[i] != NULL; i++)
{
if (str_array[i] != NULL)
free(str_array[i]);
str_array[i] = NULL;
}
free(str_array);
str_array = NULL;
}
/**
* is_delim - checks if a character is a delimiter
* @c: character to check
* @delim: delimiters
* Return: 1 if true, 0 if false
*/
int is_delim(char c, char *delim)
{
int i;
for (i = 0; delim[i] != '\0'; i++)
if (c == delim[i])
return (1);
return (0);
}
/**
* _strtok - tokenizes a string
* @str: string to tokenize
* @delim: delimiters
* Return: pointer to next token
*/
char *_strtok(char *str, char *delim)
{
static char *next;
char *token;
if (str == NULL)
str = next;
if (str == NULL)
return (NULL);
while (1)
{
if (is_delim(*str, delim))
{
str++;
continue;
}
if (*str == '\0')
{
next = NULL;
return (NULL);
}
break;
}
token = str;
while (*str != '\0')
{
if (is_delim(*str, delim))
{
*str = '\0';
next = str + 1;
return (token);
}
if (*str == '\0')
{
next = NULL;
return (token);
}
str++;
}
next = NULL;
return (token);
}
/**
* _strncmp - compare two strings
* @s1: first string
* @s2: second string
* @n: number of characters to compare
* Return: 0 if strings are equal, otherwise difference between first
*/
int _strncmp(char *s1, char *s2, int n)
{
int i;
for (i = 0; i < n && s1[i] == s2[i]; i++)
if (s1[i] == '\0')
return (0);
if (i == n)
return (0);
return (s1[i] - s2[i]);
}
/**
* _str_to_word_array - splits a string into words
* @str: string to split
* @delim: delimiters
* Return: pointer to array of words
*/
char **_str_to_word_array(char *str, char *delim)
{
char **array = NULL;
char *token;
int i = 0;
token = _strtok(str, delim);
while (token != NULL)
{
array = _realloc(array, i * sizeof(char *), (i + 1) * sizeof(char *));
array[i] = _strdup(token);
token = _strtok(NULL, delim);
i++;
}
array = _realloc(array, i * sizeof(char *), (i + 1) * sizeof(char *));
array[i] = NULL;
return (array);
}