C语言 trim函数实现

#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;
}

 

posted on 2018-10-31 10:51  末末的爸爸  阅读(316)  评论(0编辑  收藏  举报

导航