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] != ''; 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;
	}

}
原文地址:https://www.cnblogs.com/Jason66661010/p/12788978.html