题目
示例
输入
It is a apple
输出
apple a is It
题解
倒序输出的操作想到了栈,单词先顺序入栈,之后再依次出栈输出
#include<bits/stdc++.h>
using namespace std;
int main()
{
string sentence;
while(getline(cin,sentence))
{
stack<string>words;//存放单词的栈
stringstream s(sentence);//字符流s
//单词入栈
string word;
while(s>>word)
words.push(word);//注意句子分割方法
//出栈输出
while(!words.empty())
{
cout<<words.top();
words.pop();
if(words.size()!=0)
cout<<" ";
}
cout<<endl;
}
}
小结
C++ string按空格分割单词
之前记得python有split()
直接将string分割为单词的操作来着,今天查了一下发现c++也有,要用到stringstream
字符流这种数据结构,代码如下:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s;
cin>>s;
stringstream str(s);//声明初始化
string out;
while (str >> out)
cout << out << endl;
}