-
Notifications
You must be signed in to change notification settings - Fork 9
/
string_helpers1.c
93 lines (83 loc) · 1.48 KB
/
string_helpers1.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
#include "holberton.h"
/**
* _strlen - returns the length of a string
* @s: string s
* Return: length of string
*/
int _strlen(char *s)
{
char *p = s;
while (*s)
s++;
return (s - p);
}
/**
* _strcat - concatenates two strings
* @dest: copy destination
* @src: copy source
* Return: concatenated string
*/
char *_strcat(char *dest, char *src)
{
char *ptr = dest + _strlen(dest);
while (*src)
*ptr++ = *src++;
*ptr = 0;
return (dest);
}
/**
* _strcmp - compares two strings
* @s1: string 1
* @s2: string 2
* Return: 1 if true, 0 if false
*/
int _strcmp(char *s1, char *s2)
{
while (*s1)
{
if (*s1 != *s2)
break;
s1++;
s2++;
}
return (*(unsigned char *)s1 - *(unsigned char *)s2);
}
/**
* _strdup - returns a pointer to a newly allocated space in memory,
* which contains a copy of the string given as a parameter.
* @str: string to be copied
* Return: copied string
*/
char *_strdup(char *str)
{
int i, len;
char *copy;
if (!str)
return (NULL);
len = _strlen(str);
copy = malloc(sizeof(char) * len + 1);
if (!copy)
{
perror("Malloc failed\n");
exit(errno);
}
for (i = 0; i < len; i++)
copy[i] = str[i];
copy[i] = 0;
return (copy);
}
/**
* *_strcpy - copies the string pointed to by src,
* including the terminating null byte
* @dest: copied string
* @src: string to be copied
* Return: pointer to new copied string
*/
char *_strcpy(char *dest, char *src)
{
char *ptr = dest;
while (*src)
*dest++ = *src++;
*dest = 0;
return (ptr);
}