题解 | #句子逆序#

句子逆序

https://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3

// 将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
// 所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
// 数据范围:输入的字符串长度满足 1≤n≤1000
//chatGBT给的答案
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
    string sentence, word;
    getline(cin, sentence);    // 读入英文句子
    stringstream ss(sentence); // 将句子转换为字符串流
    vector<string> words;      // 存储单词的字符串数组
    while (ss >> word)
    { // 按空格分割字符串
        words.push_back(word);
    }
    for (int i = words.size() - 1; i >= 0; i--)
    { // 逆序遍历字符串数组并打印输出
        cout << words[i];
        if (i > 0)
        {
            cout << " "; // 在单词之间添加空格
        }
    }
    cout << endl;
    return 0;
}

全部评论

相关推荐

那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务