c语言什么代替8个空格,C语言K&R习题系列――句子中一个空格代替多个空格的四种方法...

原题:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

第一种:

这种最常用,设置一个inspace作为布尔变量,标志当前输入是否在字符中,或在字符外

#include 

int main(void)

{

int c;

int inspace=0;

while((c = getchar()) != EOF)

{

if(c == ' ')

{

if(inspace == 0)

{

inspace = 1;

putchar(c);

}

}

else

{

inspace = 0;

putchar(c);

}

}

return 0;

}

第二种:自己想的,虽然效果差不多,不过思路不一样

number作为标志位,记录空格的个数

#include 

main ( void )

{

int c;

int number;

number = 0;//initialization space numbers

while ( ( c = getchar() ) != EOF )

{

if ( c == ' ' )

{

++number;

if ( number == 1 )

putchar( c );

}

if ( c != ' ' )

{

putchar( c );

number = 0;

}

}

return 0;

}

第三种:

使用一个while循环来“承接”多个空格

#include 

main ( void )

{

int c;

while ( ( c = getchar() ) != EOF )

{

if ( ' ' == c )

{

putchar ( c );

while ( ( c = getchar() ) == ' ' && c != EOF )

;

}

if ( EOF == c )

break;

putchar ( c );

}

return 0;

}

第四种:

使用一个字符pc作为“当前字符”之前的字符,通过pc来判断其后的空格是否输出

#include 

int main()

{

int c, pc;

pc = EOF;

while ((c = getchar()) != EOF) {

if (c == ' ')

if (pc != ' ')

putchar(c);

if (c != ' ')

putchar(c);

pc = c;

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值