This repository has been archived by the owner on Nov 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft_substr.c
46 lines (41 loc) · 1.57 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: mcombeau <mcombeau@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 16:50:44 by mcombeau #+# #+# */
/* Updated: 2021/12/02 16:53:34 by mcombeau ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION :
The function ft_substr extracts a substring from the given string by
allocating sufficient memory for the new string starting at index start
and ending at len characters.
RETURN VALUE :
A pointer to the new string.
NULL if the memory allocation fails.
*/
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *res;
char *src;
size_t reslen;
if (!s)
return (NULL);
if (ft_strlen(s) < (size_t)start)
return (ft_strdup(""));
src = (char *)s + start;
if (ft_strlen(src) < len)
reslen = ft_strlen(src) + 1;
else
reslen = len + 1;
res = malloc(reslen * sizeof(char));
if (!res)
return (NULL);
ft_strlcpy(res, src, reslen);
return (res);
}