-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_functions_2.c
148 lines (117 loc) · 2.43 KB
/
string_functions_2.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
136
137
138
139
140
141
142
143
144
145
146
147
#include "shell.h"
/**
* strtok_delims - Splits a string into words using multiple delimiters
* @string: String to tokenize
* @delim: A string of delimiters
* Return: An array of strings on success
* Or NULL if failed
*/
char *strtok_delims(char *string, char *delim)
{
static char *nextToken;
char *token;
if (string != NULL)
nextToken = string;
if (nextToken == NULL)
return (NULL);
while (*nextToken != '\0' && delim_checker(delim, *nextToken))
nextToken++;
if (*nextToken == '\0')
return (NULL);
token = nextToken;
while (*nextToken != '\0' && !delim_checker(delim, *nextToken))
nextToken++;
if (*nextToken != '\0')
*nextToken++ = '\0';
return (token);
}
/**
* delim_checker - Inspects a character to check if it is a delimiter
* @string: String to inspect
* @delimiter: Delimiter
* Return: 1 if character matches delim
* 0 if there is no match found
*/
char *delim_checker(char *string, int delimiter)
{
while (*string != '\0')
{
if (*string == delimiter)
return (string);
string++;
}
return (NULL);
}
/**
* sh_getchar - Reads a character from stdin
* Return: The character read (tyypecast as an int)
*/
int sh_getchar(void)
{
char ch;
if (read(0, &ch, 1) == 1)
return ((int)ch);
else
return (EOF);
}
/**
* itostr - Converts an integer to a string.
* @num: The integer to be converted.
*
* Return: A dynamically allocated string containing the integer.
*/
char *itostr(int num)
{
char *str;
int idx, temp = num;
int no_of_digs = (num == 0) ? 1 : 0;
while (temp != 0)
{
no_of_digs++;
temp /= 10;
}
str = (char *)malloc(no_of_digs + 1);
if (str == NULL)
return (NULL);
idx = no_of_digs - 1;
while (idx >= 0)
{
str[idx] = '0' + (num % 10);
num /= 10;
idx--;
}
str[no_of_digs] = '\0';
return (str);
}
/**
* atoi_ - Converts a string to an integer
* @string: String to convert to integeger
* Return: The number converted from the string
* 0 if no number is found
*/
int atoi_(char *string)
{
int idx = 0, d = 0, n = 0, length = 0, f = 0, digit = 0;
while (string[length] != '\0')
length++;
while (idx < length && f == 0)
{
if (string[idx] == '-')
++d;
if (string[idx] >= '0' && string[idx] <= '9')
{
digit = string[idx] - '0';
if (d % 2)
digit = -digit;
n = n * 10 + digit;
f = 1;
if (string[idx + 1] < '0' || string[idx + 1] > '9')
break;
f = 0;
}
idx++;
}
if (f == 0)
return (0);
return (n);
}