-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_substr.c
46 lines (42 loc) · 1.53 KB
/
ft_substr.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdahlstr <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/24 16:03:54 by mdahlstr #+# #+# */
/* Updated: 2024/04/30 14:07:04 by mdahlstr ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *substr;
size_t i;
unsigned int s_len;
if (!s)
return (NULL);
s_len = ft_strlen(s);
if (start >= s_len)
return (ft_strdup(""));
if (len > s_len - start)
len = s_len - start;
substr = malloc(sizeof(char) * (len + 1));
if (!substr)
return (0);
i = 0;
while (i < len)
{
substr[i] = s[start + i];
i++;
}
substr[i] = '\0';
return (substr);
}
/* Allocates (with malloc(3)) and returns a substring
from the string ’s’. The substring begins at index
’start’ and is of maximum size ’len’.
Return value:
The substring.
NULL if the allocation fails. */