-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_substr.c
71 lines (63 loc) · 1.85 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_substr.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ael-haib <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/21 13:15:37 by ael-haib #+# #+# */
/* Updated: 2024/01/26 21:38:24 by ael-haib ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_substr_len(char const *s, unsigned int start, size_t len)
{
size_t str_len;
int sec_len;
str_len = ft_strlen(s);
if (start >= str_len)
sec_len = 0;
else if (start + len > str_len)
sec_len = str_len - start;
else
sec_len = len;
return (sec_len);
}
char *ft_substr(char const *s, unsigned int start, size_t len)
{
size_t sec_len;
char *substring;
char *dest_ptr;
if (s == NULL || len < 0)
return (NULL);
sec_len = ft_substr_len(s, start, len);
substring = malloc((sec_len + 1) * sizeof(char));
if (substring == NULL)
return (NULL);
dest_ptr = substring;
while (*s && start--)
s++;
while (*s && len--)
{
*dest_ptr = *s;
dest_ptr++;
s++;
}
*dest_ptr = '\0';
return (substring);
}
/* int main(void)
{
const char *original = "Amine el haiba";
char *result = ft_substr(original, 400, 20);
if (result != NULL)
{
printf("Substring is :%s\n", result);
free(result);
}
else
{
printf("wrong input : Error\n");
}
return (0);
} */