-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrim.c
45 lines (36 loc) · 1.02 KB
/
trim.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
#include "trim.h"
#include <string.h>
#include <ctype.h>
char *trim(char *str)
{
size_t len = 0;
char *frontp = str;
char *endp = NULL;
if( str == NULL ) { return NULL; }
if( str[0] == '\0' ) { return str; }
len = strlen(str);
endp = str + len;
/* Move the front and back pointers to address the first non-whitespace
* characters from each end.
*/
while( isspace(*frontp) ) { ++frontp; }
if( endp != frontp )
{
while( isspace(*(--endp)) && endp != frontp ) {}
}
if( str + len - 1 != endp )
*(endp + 1) = '\0';
else if( frontp != str && endp == frontp )
*str = '\0';
/* Shift the string so that it starts at str so that if it's dynamically
* allocated, we can still free it on the returned pointer. Note the reuse
* of endp to mean the front of the string buffer now.
*/
endp = str;
if( frontp != str )
{
while( *frontp ) { *endp++ = *frontp++; }
*endp = '\0';
}
return str;
}