寻找输入中的相邻相同行

Q: 编写一个程序,从标准输入一行一行地读取文本,如果相邻出现重复内容,则打印出其中一行,其余的不打印.

程序具体要求:

如果文件中有2行或更多相邻的文本内容相同,那么久打印出其中一行,其余的行不打印。假设文件中文本行在长度上不会超过128个字符,(127个字符加上用于终结文本行的换行符)。

考虑下面的输入文件。
This is the first line.
Another line.
And another.
And another.
And another.
And another.
Still more.
Almost done now --
Almost done now --
Another line.
Still more.
Finished.

假设所有的行在尾部没有任何空白,程序应该输出:


And another.
Almost done now --

所有内容相同的相邻文本行有一行被打印,注意“Another line”和“Still more”并未打印,因为它们虽然各占2行,但相同文本行的位置并不相邻。

提示:使用gets函数读取行,使用strcpy函数来复制,使用strcmp函数进行比较。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
	char *lastStr[128];
	char *currentStr[128];
	int theSameLineCount = 0;
	while(gets(currentStr) != NULL) {
		if (strcmp(lastStr, currentStr) == 0) {
			theSameLineCount++;
		} else {
			if (theSameLineCount > 0) {
				printf("\t>>>%s\n", lastStr);
			}
			theSameLineCount = 0;
		}
		strcpy(lastStr, currentStr);
		printf("\t%d\n", theSameLineCount);
	}
	system("pause");
	return 0;
}

测试的结果:

This is the first line.
	0
Another line.
	0
And another.
	0
And another.
	1
And another.
	2
And another.
	3
Still more.
	>>>And another.
	0
Almost done now --
	0
Almost done now --
	1
Another line.
	>>>Almost done now --
	0
Still more.
	0
Finished.
	0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值