删除字符串中多余的空格 shrink_space

 

/*********************************************************************
NAME
        shrink_space - shrink one or more space to one space.

SYNOPSIS
        char *shrink_space(char *dest, char const *src, size_t n);

DESCRIPTION
        shrink one or more space to one space, space characters
include : ' ', '\n', '\r', '\t' these four characters.

**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
char *shrink_space(char *dest, char const *src, size_t n)
{
    int i = 0, isspace = 0;
   
    char *ret = dest;
    if (NULL == src || NULL == dest)
    {
        printf("src or dest is NULL\n");
        return ret;
    }
   
    *dest++ = *src;             
    for (i = 1; i < n; i++)
    { 
        if ('\t' == *src ||' ' == *src ||'\n' == *src ||'\r' == *src)    // check  if preceding charater is a space. 
        {
            isspace = 1;   
        }
        else
        {
            isspace = 0;       
        }
       
        src++;       
        if ((isspace == 1) && ('\t' == *src ||' ' == *src ||'\n' == *src ||'\r' == *src)) // check if the next charater is a space.
        {
           continue;    // if preceding charater is space and the next is space too, ignore the charater.
        }
        *dest++ = *src;                
    }
    *dest = '\0';
  
    return ret;
}

int main(void)
{
    int n = 0;
    char a[] = "    This Content hoho        is ok  \
                      ok?\
                      \
                      file system\
                uttered words   ok  ok     ?\
                end.";
    char *dest = NULL;
   
    n = sizeof(a);
    printf("n = %d\n", n);
    dest = (char *)malloc(n);
    printf("\n%s\n", a);
    printf("%s\n", shrink_space(dest, a, n));
    free(dest);
    dest = NULL;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值