C++ 程序:反转英文句子中的单词顺序

本程序使用 C++ 语言编写,旨在读取一行英文句子,将所有单词的顺序倒排并输出,单词间以单个空格分隔。

输入描述

输入为一个字符串(字符串长度至多为 100),只包含字母和空格,单词间以单个空格分隔。

输出描述

输出为按要求排序后的字符串,单词间以单个空格分隔。

用例输入 1

'I am a student'

用例输出 1

'student a am I'

C++ 代码实现

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    string input;
    getline(cin, input);
    
    stringstream ss(input);
    vector<string> words;
    string word;
    
    while (ss >> word) {
        words.push_back(word);
    }
    
    reverse(words.begin(), words.end());
    
    for (int i = 0; i < words.size(); i++) {
        cout << words[i] << " ";
    }
    
    return 0;
}

程序解析

  1. 使用 getline(cin, input) 读取输入的英文句子。
  2. 使用 stringstream 对象将输入句子分解成单词。
  3. 使用 vector 容器存储所有单词。
  4. 使用 reverse 函数将 vector 中的单词顺序反转。
  5. 使用循环遍历 vector,输出反转后的单词序列。

程序原理

程序利用了 stringstream 对象的特性,将输入字符串按空格分解成单个单词,并将这些单词存入 vector 容器中。然后,使用 reverse 函数将 vector 中的元素顺序反转,最后输出反转后的单词序列。


原文地址: https://www.cveoy.top/t/topic/p658 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录