题解 | #句子逆序#
句子逆序
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;
}
查看20道真题和解析