杭电OJ 1062 Text Reverse(C)

Problem Description

Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single line with several words. There will be at most 1000 characters in a line.

Output
For each test case, you should output the text which is processed.

Sample Input
3
olleh !dlrow
m’I morf .udh
I ekil .mca

Sample Output
hello world!
I’m from hdu.
I like acm.

Hint
Remember to use getchar() to read ‘\n’ after the interger T, then you may use gets() to read a line and process it

**分析:**题目不难,属于那种看到就有思路的。唯一的陷阱题目也给了提示,即读取输入行数后按下的回车键。这里唯一的疑惑可能是字符串中的空格如何输出,是按照给定的字符串输出,还是只输出一个(没错,是我这个憨憨有这个疑惑)。我依次写了代码去尝试了,前者是AC的,后者则提示格式不对。。。好了,废话不多说,AC代码如下:
附:我看见有些代码是对字符串进行反转后再输出的,我觉得这有些多余了,直接倒序输出即可,不必给代码增加复杂度。

#include<iostream>
#include<cstring>
using namespace std;
char ch[1500][1000],s[1500];
int main()
{
	int n;
	while(cin>>n)
	{
		getchar();   //读取'\n'
		while(n--)
		{
			gets(s);  
			int h=0,l=0,cnt=0;
			for(int i=0;i<=strlen(s);i++)
			{
				if(s[i]!=' '&&s[i]!='\0') {  //如果不读取到'\0'则最后一个字符串不会打印
					ch[h][l++]=s[i];
				}
				else{
					if(s[i]==' ') cnt++;  //记录空格个数
					for(int i=l-1;i>=0;i--) printf("%c",ch[h][i]); //倒序输出
					while(cnt--) printf(" "); //输出空格
					ch[h][l]='\0'; //字符串完结
					cnt=0;h++; //空格数置0,否则上面空格输出会错误
					l=0; //准备下一字符串读取
				}
			}
			printf("\n"); //输出换行
		}
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值