-
Notifications
You must be signed in to change notification settings - Fork 3
/
util_funcs1.c
99 lines (82 loc) · 1.76 KB
/
util_funcs1.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
#include "shell.h"
/**
* my_strlen - gets the length of a string
* @str: string to count
* Return: no of chars in the string
*/
int my_strlen(char *str)
{
int len;
for (len = 0; str[len] != '\0'; len++)
;
return (len);
}
/**
* my_strcpy - copies a string to another. destination needs to be malloc'd
* @destination: container to insert copy
* @source: string to be copied
*
* Return: a pointer to the destination
*/
char *my_strcpy(char *destination, char *source)
{
int i;
for (i = 0; source[i] != '\0'; i++)
destination[i] = source[i];
destination[i] = '\0';
return (destination);
}
/**
* my_strcat - appends source to destination. malloc destination before call
* @destination: an existing string
* @source: string to be appended to destination
* Return: a pointer to the destination
*/
char *my_strcat(char *destination, char *source)
{
int i, j;
for (i = 0; destination[i] != '\0'; i++)
;
for (j = 0; source[j] != '\0'; j++, i++)
destination[i] = source[j];
destination[i] = '\0';
return (destination);
}
/**
* my_strcmp - compares two strings
* @str1: string1
* @str2: string 2 to compare with
* Return: int representing if true or not
*/
int my_strcmp(char *str1, char *str2)
{
int n, d;
for (n = 0, d = 0; (str1[n] != '\0' || str2[n] != '\0'); n++)
{
d = str1[n] - str2[n];
if (d != 0)
break;
}
if (d < 0)
return (-1);
else if (d > 0)
return (1);
return (d);
}
/**
* my_strdup - duplicates a string, allocating the appropriate size to the copy
* @str: to be duplicated
*
* Return: pointer to the duplicated string
*/
char *my_strdup(char *str)
{
char *dup;
size_t len;
len = my_strlen(str);
dup = malloc(sizeof(char) * (len + 1));
if (dup == NULL)
return (NULL);
my_memcpy(dup, str, len + 1);
return (dup);
}