-
Notifications
You must be signed in to change notification settings - Fork 2
/
string_funcs_1.c
128 lines (106 loc) · 1.84 KB
/
string_funcs_1.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
#include "shell.h"
/**
* _strdup - allocate memory for a string to duplicate
* @str: string to duplicate
*
* Return: new string on success, NULL on failure
*/
char *_strdup(char *str)
{
char *dup = NULL;
int c, i = 0;
if (!str)
return (NULL);
while (str[i])
i++;
dup = malloc(sizeof(char) * i + 1);
if (!dup)
return (NULL);
for (c = 0; c < i; c++)
dup[c] = str[c];
dup[c] = '\0';
return (dup);
}
/**
* str_concat - concatenates two strings,
* and allocate memory for the result string
* @s1: string to concatenate
* @s2: other string to concatenate
*
* Return: pointer to the string created on success, or NULL on failure
*/
char *str_concat(char *s1, char *s2)
{
char *s3 = NULL;
unsigned int i = 0, j = 0, len1 = 0, len2 = 0;
len1 = _strlen(s1);
len2 = _strlen(s2);
s3 = malloc(sizeof(char) * (len1 + len2 + 1));
if (s3 == NULL)
return (NULL);
i = 0;
j = 0;
if (s1)
{
while (i < len1)
{
s3[i] = s1[i];
i++;
}
}
if (s2)
{
while (i < (len1 + len2))
{
s3[i] = s2[j];
i++;
j++;
}
}
s3[i] = '\0';
return (s3);
}
/**
* _strcmp - compares two strings
* @s1: first string to compare
* @s2: second string to compare
*
* Return: less than 0 if s1 is less than s2, 0 if they're equal,
* more than 0 if s1 is greater than s2
*/
int _strcmp(char *s1, char *s2)
{
while (*s1 == *s2)
{
if (*s1 == '\0')
{
return (0);
}
s1++;
s2++;
}
return (*s1 - *s2);
}
/**
* _strncmp - compare strings up to n bytes
* @s1: string to compare against
* @s2: string to compare from
* @n: number of bytes to compare
*
* Return: 0 if the strings are different, non-zero if they are the same
*/
int _strncmp(char *s1, char *s2, unsigned int n)
{
unsigned int i = 0;
while (*s1 == *s2 && i < n)
{
if (*s1 == '\0')
{
return (0);
}
s1++;
s2++;
i++;
}
return (i != n);
}