K&R C Exercise 1-9 Solution

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


下面给出两种求解思路,第一种方法考虑输出字符的条件,不难看出,当当前字符为非空格时以及当前字符为空格,而上一个字符为非空格时,应当输出当前字符。为保存上一字符,需借助变量lastc来保存。

int main()
{
	int c, last_c;

	last_c = 'a';
	while( ( c = getchar() ) != EOF )
	{
		if( c != ' ' || last_c != ' ' )
			putchar( c );
		last_c = c;
	}
	return 0;
}
下面是另一种思路:头一次遇到空格或制表符时,输出一个空格,此后直到遇见非空格或非制表符时才输出下一字符。
// 方法 2
int main()
{
	int c;
	while( ( c = getchar() ) != EOF )
	{
		if( c != ' ' && c != '\t' )
			putchar( c );
		else if( c == ' ' || c == '\t' )
		{
			putchar( ' ' );
			c = getchar();
			while( c == ' ' || c == '\t' )
				c = getchar();
		}
	}
	return 0;
}

你可能感兴趣的:(c,String,input,each,output)