-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_substr.c
executable file
·57 lines (50 loc) · 1.78 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
47
48
49
50
51
52
53
54
55
56
57
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jchoy-me <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/11 14:29:37 by jchoy-me #+# #+# */
/* Updated: 2023/07/17 16:32:53 by jchoy-me ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION:
Allocates (with malloc(3)) and returns a substring from the string ’s’.
The substring begins at index ’start’ and is of maximum size ’len’.
PARAMETERS:
s: The string from which to create the substring.
start: The start index of the substring in the string ’s’.
len: The maximum length of the substring.
RETURN VALUE:
The substring.
NULL if the allocation fails.
EXTERNAL FUNCTIONS:
malloc
*/
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *sbstr;
size_t i;
size_t strsize;
i = 0;
if (s == NULL)
return (NULL);
strsize = ft_strlen(s);
if (len > strsize - start)
len = strsize - start;
if (start > strsize)
len = 0;
sbstr = (char *) malloc(sizeof(char) * (len + 1));
if (sbstr == NULL)
return (NULL);
while (i < len && s[start + i] != '\0' && start < strsize)
{
sbstr[i] = s[start + i];
i++;
}
sbstr[i] = '\0';
return (sbstr);
}