(code jam)Problem B. Reverse Words

本文介绍了一种使用C++来反转给定文本行中单词顺序的方法,并提供了两种不同的实现方式,一种是通过逐字符读取并反转,另一种则是利用了C++标准库中的字符串流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.

Input

The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.

Output

For each test case, output one line containing "Case #x: " followed by the list of words in reverse order.

Limits

Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000

Sample


Input 

Output 
3
this is a test
foobar
all your base
Case #1: test a is this
Case #2: foobar
Case #3: base your all

看输入数据就知道是把单词颠倒过来。想起以前有种getline的字符串操作,用起来不错,就是记性不好,记不住怎么用了。两份代码。。。

#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
char a[1010];
int main()
{
	int t;
	freopen("B-large-practice.in","r",stdin);
	freopen("output.out","w",stdout);
	scanf("%d",&t);
	getchar();
	int h=0;
	while (t--)
	{
		int j;
		char s[1010];
		gets(s);
		int l=strlen(s)-1;
		printf("Case #%d: ",++h);
		while (l>=0)
		{
			int i=0;
			while (s[l]!=' ' && l>=0)
			{
				a[i++]=s[l];
				l--;
			}
			for (j=i-1;j>=0;j--)
				cout<<a[j];
			if (l==-1)
			{
				printf("\n");
				break;
			}
			else printf(" ");
			l--;
		}
	}
	return 0;
}


#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;
char a[1010][1010];
int main()
{
	int t;
	freopen("B-large-practice.in","r",stdin);
	freopen("output.out","w",stdout);
	scanf("%d",&t);
	getchar();
	int h=0;
	while (t--)
	{
		string line,ss;
		while (getline(cin,line))
		{
			istringstream s(line);
			int i=0,j;
			while (s>>a[i++]);
			printf("Case #%d: ",++h);
			for (j=i-2;j>0;j--)
				cout<<a[j]<<" ";
			cout<<a[0]<<endl;
		}
		
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值