题目描述
编写程序,读入一行英文(只包含字母和空格,单词间以单个空格分隔),将所有单词的顺序倒排并输出,依然以单个空格分隔。
输入格式
输入为一个字符串(字符串长度至多为 100)。
输出格式
输出为按要求排序后的字符串。
Sample Input
I am a student
Sample Output
student a am I
思路
题意就是,读入单词,反向输出。
C++代码1:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string str, temp = "";
stack<string> s;
getline(cin, str);
int len = str.length();
for(int i = 0; i < len; i++)
{
if((str[i] <= 'z' && str[i] >= 'a') || (str[i] <= 'Z' && str[i] >= 'A'))
{
temp += str[i];
while((str[i + 1] <= 'z' && str[i + 1] >= 'a') || (str[i + 1] <= 'Z' && str[i + 1] >= 'A'))
{
temp += str[i + 1];
i++;
}
s.push(temp);
temp = "";
}
}
while(!s.empty())
{
cout << s.top();
s.pop();
if(!s.empty()) cout<<" ";
}
return 0;
}
C++代码2:
#include<iostream>
using namespace std;
const int N = 1e5;
string a[N];
int main()
{
int len = 0;
while(cin >> a[len])
len++;
cout << a[len - 1];
for(int i = len - 2;i >= 0; i--)
cout <<" " << a[i];
return 0;
}