{ }codelper
分割字符串连接字符串反转列表P0028

反转单词顺序

给出一行由小写英文字母和数字组成、用空格分隔的单词。
单词之间可能有一个或多个空格,行首和行尾也可能有空格。
把单词顺序反过来,单词之间恰好用一个空格分隔,输出为一行。
每个单词内部的字母顺序保持不变。
行首和行尾不要输出空格。

输入
行长度 1 到 1,000,至少一个单词
输出
反序的单词,用一个空格分隔
样例 1 · stdin
the quick brown fox
stdout
fox brown quick the
样例 2 · stdin
  keep   it  simple 
stdout
simple it keep
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

分割 → 反转 → 连接,三步都一样,只是名字不同。
分割:Python split()(无参数),JS/TS trim().split(/\s+/),Java trim().split("\\s+"),C# Split(' ', StringSplitOptions.RemoveEmptyEntries),Craykon 分割()。
C 和 C++ 的 scanf("%s")、cin >> 会自动跳过空格。
反转:Python reversed,JS reverse()(会改变数组本身),Java Collections.reverse,C# Array.Reverse,C++ std::reverse,Craykon 反转()。
连接:Python " ".join,Java String.join,C# string.Join,Craykon 连接(" ")。
陷阱:像 split(" ") 这样按单个空格分割,空格连续的地方会产生空片段,连接后会出现重叠的空格。
反转整个字符串会连单词内部的字母也反过来。

Pythonmain.py · 2 行
words = input().split()print(" ".join(reversed(words)))
JavaScriptmain.js · 3 行
const line = require("fs").readFileSync(0, "utf8").split("\n")[0];const words = line.trim().split(/\s+/);console.log(words.reverse().join(" "));
TypeScriptmain.ts · 4 行
import { readFileSync } from "node:fs";const line: string = readFileSync(0, "utf8").split("\n")[0];const words: string[] = line.trim().split(/\s+/);console.log(words.reverse().join(" "));
JavaMain.java · 14 行
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Arrays;import java.util.Collections;import java.util.List; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        List<String> words = Arrays.asList(br.readLine().trim().split("\\s+"));        Collections.reverse(words);        System.out.println(String.join(" ", words));    }}
C#Main.cs · 11 行
using System; class Program{    static void Main()    {        string[] words = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        Array.Reverse(words);        Console.WriteLine(string.Join(" ", words));    }}
C++main.cpp · 16 行
#include <algorithm>#include <iostream>#include <string>#include <vector> int main() {    std::vector<std::string> words;    std::string w;    while (std::cin >> w) words.push_back(w);    std::reverse(words.begin(), words.end());    for (size_t i = 0; i < words.size(); i++) {        if (i > 0) std::cout << ' ';        std::cout << words[i];    }    std::cout << "\n";}
Cmain.c · 13 行
#include <stdio.h> static char words[500][1001]; int main(void) {    int n = 0;    while (n < 500 && scanf("%1000s", words[n]) == 1) n++;    for (int i = n - 1; i >= 0; i--) {        printf("%s", words[i]);        putchar(i > 0 ? ' ' : '\n');    }    return 0;}
Craykonmain.cray · 3 行
words = 控制台.读行().分割();words.反转();控制台.输出(words.连接(" "));