-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrim.c
More file actions
80 lines (73 loc) · 1.64 KB
/
trim.c
File metadata and controls
80 lines (73 loc) · 1.64 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
#include "shell.h"
/**
* trim - remove the left and right whitespaces in a string
* @str: address of string to modify
*
* Description: If trimmed, the string will be shorted and the unnecessary
* bytes removed
*
* Return: the modified string else NULL on error
*/
char *trim(char **str)
{
char *new = NULL, *string = NULL, comment = '#';
const char DELIM = ' ';
unsigned int start = 0, end = 0;
int size = 0, comment_start = 0;
if (str == NULL || *str == NULL || strlen(*str) == 0)
{
return (NULL);
}
string = *str;
for (start = 0; string[start] && string[start] == DELIM; start++)
;
for (end = strlen(string); end > 0 && string[end - 1] == DELIM; end--)
;
comment_start = find_chr(string, comment);
end = (comment_start > 0) ? (unsigned int)comment_start - 1 : end;
end = (comment_start == 0) ? 0 : end;
size = (end == 0) ? 0 : end - start;
if (size <= 0)
{
free_str_safe(&*str);
*str = NULL;
return (NULL);
}
new = malloc((size + 1) * sizeof(char));
if (new == NULL)
{
return (NULL);
}
new = strncpy(new, string + start, size);
new[size] = '\0';
free_str_safe(&string);
string = new;
*str = string;
return (*str);
}
/**
* find_chr - returns the index of the first occurrence of a character
* in a string
* @str: string to searchh
* @c: character to match
* Description: index starts from 0
*
* Return: index of character else -1 if not found
* else -2 on error
*/
int find_chr(const char *str, const char c)
{
char *index = NULL;
int pos = 0;
if (str == NULL)
{
return (-2);
}
index = strchr(str, c);
if (index == NULL)
{/* not found */
return (-1);
}
pos = (int)(index - str);
return (pos);
}