Created
May 4, 2018 08:52
-
-
Save ustbgaofan/b8319219e58dda7bc30f7af472ebbc8f to your computer and use it in GitHub Desktop.
trim the blank in the head or in the tail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
//erase the blank int the tail | |
char *rtrim(char *str) | |
{ | |
if(NULL == str || *str == '\0') | |
{ | |
return str; | |
} | |
int len = strlen(str); | |
char *p = str + len - 1; | |
while( p >= str && isspace(*p)) | |
{ | |
*p = '\0'; | |
--p; | |
} | |
return str; | |
} | |
//erase the blank in the head | |
char *ltrim(char *str) | |
{ | |
if( NULL == str || *str == '\0') | |
{ | |
return str; | |
} | |
int len = 0; | |
char *p = str; | |
while(*p != '\0' && isspace(*p)) | |
{ | |
++p; | |
++len; | |
} | |
memmove(str,p, strlen(str) - len + 1); | |
return str; | |
} | |
char* trim(char *str) | |
{ | |
str = rtrim(str); | |
str = ltrim(str); | |
return str; | |
} | |
void demo() | |
{ | |
char str[] = " ab c "; | |
printf("before trim:%s\n", str); | |
char *p = trim(str); | |
printf("after trim:%s\n", p); | |
} | |
int main(int argc, char **argv) | |
{ | |
demo(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment