-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strtrim.c
65 lines (57 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtrim.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aviholai <aviholai@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/18 13:42:05 by aviholai #+# #+# */
/* Updated: 2022/02/07 15:55:37 by aviholai ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** 'Strtrim()' (string trim) allocates memory for for a copy of the applied
** string 's' and trims all the whitespaces from the beginning and of the
** string and then returns it. If allocation fails, returns 'NULL'.
** Uses the contributing functions 'ft_startfinder()' and 'ft_endfinder()' to
** measure an index for when the whitespace ends and starts for the string.
*/
static int ft_startfinder(const char *s)
{
int index;
index = 0;
while (s[index])
{
if (s[index] != ' ' && s[index] != '\t' && s[index] != '\n')
return (index);
index++;
}
return (-1);
}
static int ft_endfinder(const char *s)
{
int index;
index = ft_strlen(s) - 1;
while (index > 0)
{
if (s[index] != ' ' && s[index] != '\t' && s[index] != '\n')
return (index);
index--;
}
return (-1);
}
char *ft_strtrim(char const *s)
{
char *result;
int start_mark;
int end_mark;
if (s == NULL)
return (NULL);
start_mark = ft_startfinder(s);
end_mark = ft_endfinder(s);
if (end_mark == -1 || start_mark == -1)
return (ft_strnew(0));
result = ft_strsub(s, start_mark, end_mark - start_mark + 1);
return (result);
}