-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strtrim.c
More file actions
85 lines (74 loc) · 2.11 KB
/
ft_strtrim.c
File metadata and controls
85 lines (74 loc) · 2.11 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fsanz-ex <fsanz-ex@student.42madrid.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/19 14:01:07 by fsanz-ex #+# #+# */
/* Updated: 2023/02/23 19:31:35 by fsanz-ex ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_starttrim(char const *s1, char const *set);
int ft_endtrim(char const *s1, char const *set);
/*Allocates (with malloc(3)) and returns a copy of ‘s1’ with the characters
specified in ‘set’ removed from the beginning and the end of the string.
Returns the trimmed string or NULL if the allocation fails.*/
char *ft_strtrim(char const *s1, char const *set)
{
int start;
int end;
char *trimmed;
if (s1 == NULL)
return (NULL);
if (set == NULL)
return (ft_strdup(s1));
start = ft_starttrim(s1, set);
end = ft_endtrim(s1, set);
if (start >= end)
return (ft_strdup(""));
trimmed = (char *) malloc(sizeof(char) * (end - start + 1));
if (trimmed == NULL)
return (NULL);
ft_strlcpy(trimmed, s1 + start, end - start + 1);
return (trimmed);
}
//Defines where to start the trim
int ft_starttrim(char const *s1, char const *set)
{
int i;
int j;
i = 0;
j = 0;
while (s1[i] && set[j])
{
if (s1[i] == set[j])
{
i++;
j = 0;
}
else
j++;
}
return (i);
}
//Defines where to end the trim
int ft_endtrim(char const *s1, char const *set)
{
int i;
int j;
i = ft_strlen(s1) - 1;
j = 0;
while (s1[i] && set[j])
{
if (s1[i] == set[j])
{
i--;
j = 0;
}
else
j++;
}
return (i + 1);
}