Skip to content

Instantly share code, notes, and snippets.

@ustbgaofan
Created May 4, 2018 08:52
Show Gist options
  • Save ustbgaofan/b8319219e58dda7bc30f7af472ebbc8f to your computer and use it in GitHub Desktop.
Save ustbgaofan/b8319219e58dda7bc30f7af472ebbc8f to your computer and use it in GitHub Desktop.
trim the blank in the head or in the tail
#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