删除字符串开始及末尾的空白符,并且把数组中间的多个空格(如果有)符转化为1个。

常规解法:

int trim(char* str)
{
    int count = 0;
    char* p = str;
    bool first = true;
    while(*str != '\0' && *str == ' '){
        count++;
        str++;
        }
        if(*str == '\0'){
            *p = '\0';
            return count;
            }
            
    while(*str != '\0'){
        while(*str != '\0' && *str != ' '){
            *p++ = *str++;
            }
        if(*str == '\0')break;
            *p++ = *str++;
              while(*str != '\0' && *str == ' '){
                      count++;
                        str++;
                           }
        }
        if(*(p-1) == ' '){
            p--;
            count++;
            }
        *p = '\0';
    return count;
    }

花花的代码几乎已经到极致了,不过不确定是否一定就是正确的,暂时只发现了一点点小问题:就是都为空格的时候不行,不过经过改进,现在的代码应该是没有问题了。

基本思路: 指针

需要两个指针, 首先除去开头的空格,这个相信大家都没有任何问题,这时字符串已经变为  a*****  这种形式了;

难度就在于,在这之后出现的空格,不能全部除去,需要保留一个。

void tri(char* p,char k)
{
        assert(p);
    char* s1 = p;
    char* s2 = p;
    while (*s2&&*s2 == k)        //先去掉开始的空格
        ++s2;
    *s1 = *s2;
    if (*s2 == '\0')               //若为全空格字符串
        return;
    while (*(++s2) != '\0')
    {
        if (*s2 != k||*s1 != k)   //核心:(<a,a>||<_,a>)s2为字符 一定要复制   <a,_> s2为空格 s1为字符 代表为首次出现空格 要复制
        {
            *(++s1) = *s2;
        }
    }
    if (*s1 == k)     // 消除最后一个空格             
        *s1 = '\0';
    else
        *(++s1) = '\0';
}    

3. GP大神的代码

void trim_str(char *str){
    assert(str);{
        int s_len = strlen(str);
        if(s_len>0){
            char *s_b = str,
                *s_e = str+s_len,
                *s_copy = str;
            for( ; s_b!=s_e && *s_b==' '; ++s_b);
            while(1){
                for( ; s_b!=s_e && *s_b!=' '; ++s_b)
                    *s_copy++ = *s_b;
                if(s_b==s_e)
                    break;
                *s_copy++ = *s_b++;
                for( ; s_b!=s_e && *s_b==' '; ++s_b);
                if(s_b==s_e){
                    --s_copy;
                    break;
                }
            }
            *s_copy = '\0';
        }
    }
}
原文地址:https://www.cnblogs.com/itachi7/p/2703118.html