-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrimit.c
71 lines (62 loc) · 2.2 KB
/
trimit.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
// file: trimit.c
// source: http://www.xappsoftware.com/wordpress/2013/11/14/a-simple-c-function-to-trim-leading-and-trailing-white-spaces-from-a-string/
// author: "GG1"
// downloaded by: bksteele, [email protected]
// since: 3/1/2017
// // // // // // // // // // // // // // // // // // // // // // // //
#include <ctype.h> // isspace
#include <string.h> // strlen
#include "trimit.h"
/*+-----------------------------------------------------------+
| Function name : trim. |
| Parameters : |
| str : the string to trim. |
| Return value : the pointer to the string. |
| : if an error occurs SU_CANNOT_W_BYTE //not true
| Description : Trims leading and trailing white spaces |
| and return the modified string. |
| The pointer to the string can be used to |
| free memory. |
+-----------------------------------------------------------+*/
/// trim leading and trailing whitespace {' ' \t \n \r}
char *trim(char *str)
{
size_t len = 0;
char *frontp = str - 1; // point off the front
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)));
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 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;
}
// // // // // // // // // // // // // // // // // // // // // // // //