C語言 trim函式實現
阿新 • • 發佈:2018-10-31
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //去除尾部空格 char *rtrim(char *str) { if(str == NULL||*str == '\0') { return str; } int len = strlen(str); char *p=str+len-1; while(isspace(*p)&&p>=str) {*p = '\0'; --p; } return str; } char *ltrim(char *str) { if(str == NULL||*str == '\0') { return str; } char *p = str; int len = 0; while(*p != NULL&&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; } int main() { char str1[] = " dfadsf "; printf("str1=%s\n",str1); char *p = trim(str1); printf("p=%s",p); //printf("***********"); return 0; }