题解 | #句子逆序#
句子逆序
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; }