-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_substr.c
99 lines (79 loc) · 2.26 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
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: musenov <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/21 21:23:10 by musenov #+# #+# */
/* Updated: 2022/12/06 16:13:00 by musenov ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *sub_s;
size_t i;
if (!s)
return (0);
if (start > ft_strlen(s))
return (ft_strdup(""));
if (len > ft_strlen(s) - start)
len = ft_strlen(s) - start;
sub_s = (char *)malloc(sizeof(*s) * (len + 1));
if (!sub_s)
return (0);
i = 0;
while (i < len)
{
*(sub_s + i++) = *(s + start++);
}
*(sub_s + i) = '\0';
return (sub_s);
}
/*
ft_substr:
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.
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’.
QUESTIONS
-/-
ANSWER
-/-
COMPARE
-/-
ALTERNATIVE SOLUTION
-/-
EXPLANATION
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *sub_s;
size_t i;
if (!s)
return (0);
if (start > ft_strlen(s))
below " ft_strdup("") " will return char pointer with '\0' at position 0
return (ft_strdup(""));
if (len > ft_strlen(s) - start)
len = ft_strlen(s) - start;
sub_s = (char *)malloc(sizeof(*s) * (len + 1));
if (!sub_s)
return (0);
i = 0;
while (i < len)
{
*(sub_s + i++) = *(s + start++);
}
*(sub_s + i) = '\0';
return (sub_s);
}
REMARK
-/-
*/