-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
127 lines (106 loc) · 1.7 KB
/
utils.c
File metadata and controls
127 lines (106 loc) · 1.7 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
#include "shell.h"
/**
* _isalpha - check if the character is
* an alphabet
* @c: character to be checked
*
* Return: 1 if it is 0 if not
*/
int _isalpha(int c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return (1);
return (0);
}
/**
* reverse - reverses string
* @str: string
* @len: string length
*/
void reverse(char *str, int len)
{
int start = 0, end = len - 1;
char temp;
while (start < end)
{
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
/**
* _itoa - converts integer to string
* @n: number to convert
*
* Return: pointer to converted string
*/
char *_itoa(int n)
{
int is_negative = 0, count = 0, temp;
int i = 0, digit, size;
char *str;
if (n < 0)
{
is_negative++;
n *= -1;
}
temp = n;
if (n != 0)
{
while (temp != 0)
{
count++;
temp /= 10;
}
} else
count = 1;
size = count + is_negative + 1;
str = malloc(sizeof(char) * size);
if (str == NULL)
return (NULL);
while (n != 0)
{
digit = n % 10;
str[i++] = (char)(digit + '0');
n /= 10;
}
if (is_negative)
str[i++] = '-';
str[i] = '\0';
reverse(str, i);
return (str);
}
/**
* _atoi - convert string to integer
* @str: string to be converted
*
* Return: converted number
*/
int _atoi(char *str)
{
int i, is_negative = 1;
int flag = 0, value;
size_t result = 0;
for (i = 0; str[i] != '\0' && flag != 2; i++)
{
if (_isalpha(str[i]))
return (-1);
if (str[i] == '-')
is_negative *= -1;
if (str[i] >= '0' && str[i] <= '9')
{
result *= 10;
result += (str[i] - '0');
flag = 1;
} else if (flag == 1)
flag = 2;
}
if (is_negative == -1)
{
value = -result;
} else
value = result;
return (value);
}