-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstring_funcs.c
More file actions
115 lines (97 loc) · 1.94 KB
/
string_funcs.c
File metadata and controls
115 lines (97 loc) · 1.94 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
#include "shell.h"
/**
* _strdup - returns a pointer to a newly allocated space in memory,
* which contains a copy of the string given as a parameter
*
* @str: string
*
* Return: pointer to duplicated string
*/
char *_strdup(char *str)
{
size_t i, size = 0;
char *s;
char *temp;
/* is the string empty? */
if (str == NULL)
return (NULL); /* ah! it is, return NULL */
/* Create a temporary pointer to keep original string unchanged */
temp = str;
while (*temp)
{
temp++;
size++;
}
size += 1; /* Add 1 for the null terminator */
s = (char *)malloc(size * sizeof(char));
if (s == NULL)
return (NULL); /* Oops, mem. allocation failed */
for (i = 0; i < size; ++i)
s[i] = str[i];
return (s); /* return pointer to duplicated string */
}
/**
* _strchr - locates a char in a string
*
* @str: string
* @c: char to be located
*
* Return: pointer to @s
*/
char *_strchr(char *str, char c)
{
/* is the string empty? */
if (str == NULL)
return (NULL); /* it is, return NULL */
while (*str != '\0')
{
if (*str == c)
{
/* return pointer to matched char */
return (str);
}
str++;
}
if (c == '\0')
return (str);
return (NULL);
}
/**
* _strncmp - Compares two strings up to a specified length.
* @str1: The first string.
* @str2: The second string.
* @n: The maximum number of characters to compare.
*
* Return: 0 if the strings are equal up to the specified length, otherwise
* the difference between the first non-matching characters.
*/
int _strncmp(const char *str1, const char *str2, size_t n)
{
size_t i = 0;
while (i < n && (str1[i] != '\0' || str2[i] != '\0'))
{
if (str1[i] != str2[i])
{
return ((int)(unsigned char)str1[i] - (int)(unsigned char)str2[i]);
}
++i;
}
return (0);
}
/**
* _strlen - returns the length of a string
*
* @s: parameter
*
* Return: length of a string
*/
int _strlen(const char *s)
{
int count = 0;
while (*s != '\0')
{
s++;
count++;
}
return (count);
}