-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.c
More file actions
137 lines (126 loc) · 2.37 KB
/
strings.c
File metadata and controls
137 lines (126 loc) · 2.37 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
134
135
136
137
#include "shs.h"
/**
* _strdup - Duplicate a string in heap memory.
*
* @s: String to duplicate.
*
* Return: Pointer to the duplicated string,
* or NULL if memory allocation fails.
*/
char *_strdup(const char *s)
{
char *new;
size_t len;
len = _strlen(s);
new = malloc(sizeof(char) * (len + 1));
if (new == NULL)
return (NULL);
_memcpy(new, s, len + 1);
return (new);
}
/**
* _strlen - Get the length of a string.
*
* @s: String to calculate the length of.
*
* Return: Length of the string.
*/
size_t _strlen(const char *s)
{
size_t len;
for (len = 0; s[len] != '\0'; len++)
{
}
return (len);
}
/**
* comp_chars - Compare characters of strings.
*
* @str: Input string.
* @delim: Delimiter.
*
* Return: 1 if the characters are equal, 0 if they are not.
*/
int comp_chars(const char str[], const char *delim)
{
unsigned int i, j, k;
for (i = 0, k = 0; str[i]; i++)
{
for (j = 0; delim[j]; j++)
{
if (str[i] == delim[j])
{
k++;
break;
}
}
}
if (i == k)
return (1);
return (0);
}
/**
* _strtok - Split a string by a delimiter.
*
* @str: Input string.
* @delim: Delimiter.
*
* Return: The next token in the string, or NULL if no more tokens are found.
*/
char *_strtok(char str[], const char *delim)
{
static char *splitted, *str_end;
char *str_start;
unsigned int i, bool;
if (str != NULL)
{
if (comp_chars(str, delim))
return (NULL);
splitted = str; /* Store first address */
i = _strlen(str);
str_end = &str[i]; /* Store last address */
}
str_start = splitted;
if (str_start == str_end) /* Reach the end */
return (NULL);
for (bool = 0; *splitted; splitted++)
{
/* Breaking loop finding the next token */
if (splitted != str_start)
if (*splitted && *(splitted - 1) == '\0')
break;
/* Replacing delimiter with null character */
for (i = 0; delim[i]; i++)
{
if (*splitted == delim[i])
{
*splitted = '\0';
if (splitted == str_start)
str_start++;
break;
}
}
if (bool == 0 && *splitted) /* Str != Delim */
bool = 1;
}
if (bool == 0) /* Str == Delim */
return (NULL);
return (str_start);
}
/**
* _isdigit - Check if a string consists of digits.
*
* @s: Input string.
*
* Return: 1 if the string consists of digits, 0 otherwise.
*/
int _isdigit(const char *s)
{
unsigned int i;
for (i = 0; s[i]; i++)
{
if (s[i] < '0' || s[i] > '9')
return (0);
}
return (1);
}