PAT (Basic Level) Practice 1009 说反话 (20分) (字符串中的查找+切割+栈)

1.题目

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:

测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。

输出格式:

每个测试用例的输出占一行,输出倒序后的句子。

输入样例:

Hello World Here I Come

输出样例:

Come I Here World Hello

2.题目分析

1.substr(a,b)截取字符串函数a是开始的index,b是结束的index+1

 3.代码

方法一:C语言

#include<stdio.h>
int main()
{
	int i, j, k = 0, t = 0;
	char a[100], b[200][100];
	gets(a);
	for (j = 0; a[j] != '\0'; j++)
	{

		if (a[j] == ' ')
		{
			t = 0;
			k++;
			continue;
		}
		b[k][t] = a[j];
		t++;
	}
	printf("%s", b[k]);

	for (i = k-1; i>=0; i--)
		printf(" %s", b[i]);
}

方法二:C++

#include<iostream>
#include<stack>
#include<string>
#include<cstring>
using namespace std;
int main()
{
	stack<string>list;
	string temp;
	getline(cin, temp);

	while (1)
	{
		int i = temp.find_first_of(" ");
		if (i == -1)
			break;
		string temp2 = temp.substr(0, i);
		temp = temp.substr(i+1, temp.length());
		list.push(temp2);
	}
	int count = 0;
	list.push(temp);
	while (!list.empty())
	{
		string temp3 = list.top(); list.pop();
		if (count == 0)
		{
			cout << temp3;
			count++;
		}
		else
			cout << " " << temp3;
	}

}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值