-
Notifications
You must be signed in to change notification settings - Fork 0
/
str_helpers.c
118 lines (97 loc) · 1.76 KB
/
str_helpers.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
#include "main.h"
/**
* _strlen - Returns the lenght of the string
* @str: char pointer to string
* Return: int representing the length of @str
*/
int _strlen(char *str)
{
int len = 0;
while (str && str[len])
len++;
return (len);
}
/**
* _strcat - Concatenate 2 strings
* @dest: Destination string
* @src: Source string
* Return: Pointer to concatenated string
*/
char *_strcat(char *dest, char *src)
{
int i = 0, j = 0, destlen = 0, srclen = 0;
destlen = _strlen(dest);
srclen = _strlen(src);
while (dest[i] != '\0')
i++;
for (; i < destlen + srclen; i++)
{
dest[i] = src[j];
j++;
}
dest[i] = '\0';
return (dest);
}
/**
* _strcmp - Compare string src and string dest
* @s1: Left side string
* @s2: Right side string
* Return: Left - Right
*/
int _strcmp(char *s1, char *s2)
{
int i;
if (!s1 && !s2)
return (0);
if (!s1)
return ((int)s2[0]);
if (!s2)
return ((int)s1[0]);
for (i = 0; s1 && i <= _strlen(s1); i++)
{
if (s1[i] != s2[i])
return (s1[i] - s2[i]);
}
return (0);
}
/**
* _strcpy - Copy string src to string dest
* @dest: Where to copy src
* @src: The string to paste to dest
* Return: Pointer to dest
*/
char *_strcpy(char *dest, char *src)
{
int i, srclen = 0;
srclen = _strlen(src);
for (i = 0; i < srclen; i++)
{
dest[i] = src[i];
}
dest[i] = '\0';
return (dest);
}
/**
* _strdup - Copy a string to a newly allocated space in the mem
* @str: The string to copy
* Return: Pointer to the newly allocated space or NULL
*/
char *_strdup(char *str)
{
int i, size;
char *ptr;
if (str == NULL)
return (NULL);
i = 0;
size = _strlen(str);
ptr = malloc((size + 1) * sizeof(char));
if (ptr == NULL)
return (NULL);
while (i < size)
{
ptr[i] = str[i];
i++;
}
ptr[i] = '\0';
return (ptr);
}