题解 | 句子逆序

#include <algorithm>
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

string reverseSentence(const string& sentence) {
    // 使用字符串流分割句子为单词
    vector<string> words;
    stringstream ss(sentence);
    string word;
    while (ss >> word) {
        words.push_back(word);
    }

    // 逆序遍历拼接为句子
    string reversedSentence;
    for (size_t i = 0; i < words.size(); ++i) {
        if (i > 0) {
            reversedSentence += " ";
        }
        reversedSentence += words[words.size() - 1 - i];
    }

    return reversedSentence;
}

int main() {
    string sentence;
    // 输入句子
    getline(cin, sentence);
    // 逆序并输出结果
    string result = reverseSentence(sentence);
    cout << result << endl;
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 14:23
steelhead:你回的有问题,让人感觉你就是来学习的
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
练习生懒羊羊:开飞机把这个公司创飞吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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