题解 | #句子逆序#

句子逆序

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

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

// 函数用于逆序单词
std::string reverseWords(const std::string& sentence) {
    std::istringstream iss(sentence);
    std::vector<std::string> words;
    std::string word;

    // 将句子分割成单词并存入vector
    while (iss >> word) {
        words.push_back(word);
    }

    // 逆序单词并重新组合成句子
    std::string reversed_sentence;
    for (auto it = words.rbegin(); it != words.rend(); ++it) {
        reversed_sentence += *it;
        if (it + 1 != words.rend()) {
            reversed_sentence += " ";
        }
    }
    return reversed_sentence;
}

int main() {
    std::string line;
    // 读取多行输入
    while (getline(std::cin, line)) {
        // 输出逆序后的句子
        std::cout << reverseWords(line) << std::endl;
    }
    return 0;
}

全部评论

相关推荐

03-11 14:28
浙江大学 设计
牛客小黄鱼:代入一下,独居女生会觉得有点可怕
点赞 评论 收藏
分享
咩咩子_:项目和图形引擎岗没啥关系,最好还是项目和岗位有相关度好点,不然真有面也不一定会问很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务