【机试备考】Day21-反转单词 | string按空格分割

题目

BUPT 2011 计算机 ProblemA (oj)
在这里插入图片描述

示例

输入

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;
}

猜你喜欢

转载自blog.csdn.net/qq_43417265/article/details/113801973