删除字符串多余空格

代码如下:

#include <stdio.h>

int is_blank( int ch );
void deblank( char string[] );

int main()
{
	char string[] = "  zhang     lei  g";
    printf( "%s \n", string );
    deblank( string );
    printf( "%s \n", string);
	return 0;
}

void deblank( char string[])
{
  	char *str_temp = string;
	char *str_src = string;
    int  IS_last_blank = 0;  

    #if 	0
	while( *str_src != '\0' )
	{
		if( is_blank(*str_src) == 0 )
  		{
			strtemp++;
			IS_last_blank = 0;
		}
		else
        {
 			if( !is_last_blank )
            {
				*strtemp++ = ' ';
	            is_last_blank = 1;	
			}
        }
		str_src++;
	}
    #endif
    
	while ( *str_src != '\0' )
	{
		if( is_blank(*str_src) )
		{
			if( !IS_last_blank )
		    {
				*str_temp++ = ' ';
	            IS_last_blank = 1;	
			}
		}
		else
		{
			*str_temp++ = *str_src;
			IS_last_blank = 0;
		}
		str_src++;
    }

	*str_temp = '\0';
}
int is_blank( int ch )
{
   	return ch == ' ' || ch == '\r' || ch == '\v' || ch == '\t' || ch == '\n' || ch == '\f' ;
}

C和指针答案上代码如下:
/*
** Shrink runs of white space in the given string to a single space.
*/
#define NUL
’\0’
void
deblank( char *string )
{
char
*dest;
char
*src;
int
ch;
/*
** Set source and destination pointers to beginning of the string, then
** move to 2nd character in string.
*/
src = string;
dest = string++;
/*
** Examine each character from the source string.
*/
while( (ch = *src++) != NUL ){
if( is_white( ch ) ){
/*
** We found white space. If we’re at the beginning of
** the string OR the previous char in the dest is not
** white space, store a blank.
*/
if( src == string || !is_white( dest[–1] ) )
*dest++ = ’ ’;
}
else {
/*
** Not white space: just store it.
*/
*dest++ = ch;
}
}
*dest = NUL;
}
int
is_white( int ch )
{
return ch == ’ ’ || ch == ’\t’ || ch == ’\v’ || ch == ’\f’ || ch == ’\n’|| ch == ’\r’;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值