-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strtrim.c
94 lines (87 loc) · 2.06 KB
/
ft_strtrim.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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_strtrim.c :+: :+: */
/* +:+ */
/* By: mgraaf <mgraaf@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/12/16 14:25:05 by mgraaf #+# #+# */
/* Updated: 2021/12/16 14:25:11 by mgraaf ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
int begin_chars(char const *s1, char const *set)
{
int i;
int j;
int char_at_begin;
j = 0;
char_at_begin = 0;
while (s1[j])
{
i = 0;
while (set[i])
{
if (s1[j] == set[i])
{
char_at_begin++;
break ;
}
i++;
}
if (set[i] == '\0')
return (char_at_begin);
j++;
}
return (char_at_begin);
}
int end_chars(char const *s1, char const *set, int len)
{
int i;
int char_at_end;
len -= 1;
char_at_end = 0;
while (len >= 0)
{
i = 0;
while (set[i])
{
if (s1[len] == set[i])
{
char_at_end++;
break ;
}
i++;
}
if (set[i] == '\0')
return (char_at_end);
len--;
}
return (char_at_end);
}
char *ft_strtrim(char const *s1, char const *set)
{
int char_at_begin;
int new_len;
int len_s1;
char *trimmed;
int i;
if ((!s1 || !set) || (!s1 && !set))
return (0);
i = 0;
char_at_begin = begin_chars(s1, set);
len_s1 = ft_strlen(s1);
new_len = len_s1 - (char_at_begin + end_chars(s1, set, len_s1));
if (new_len <= 0)
new_len = 1;
trimmed = malloc((new_len * sizeof(char)) + 1);
if (!trimmed)
return (0);
while (i < new_len)
{
trimmed[i] = s1[char_at_begin + i];
i++;
}
trimmed[i] = '\0';
return (trimmed);
}