1009 说反话 (20)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。
输出格式:每个测试用例的输出占一行,输出倒序后的句子。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
思路:
标记每一个单词的首位、末尾所在的数组编号进行输出
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string s;
//cin >> s;
getline(cin,s);
string temp[80];
int j = 0;
int count = 0;
int num = 0;
int mark[80];
mark[count++] = 0;//第一个下标是0
for (int i = 0; i < s.length(); i++)
{
if (s[i] != ' '&&s[i]!='/0')
{
temp[j++] = s[i];
}
else
{
mark[count++] = j - 1;
mark[count++] = j;
num++;
}
}
num++;
mark[count] = --j;//最后一位的下标
//输出
for (int m = num*2; m >2; m=m-2)
{
for (int i = mark[m-2]; i <= mark[m-1]; i++)
cout << temp[i];
cout << " ";
}
for (int i = mark[0]; i <= mark[1]; i++)
cout << temp[i];
system("pause");
return 0;
}
优化:
利用栈来实现倒序输出,将每一个单词压入栈中,最后再依次弹出
要用Ctrl+z退出循环
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack<string> str;
string s;
while (cin>>s)
{
str.push(s);
}
cout << str.top();
str.pop();
while (str.empty()==0)
{
cout << " ";
cout << str.top();
str.pop();
}
system("pause");
return 0;
}