{ }codelper
文字列の分割文字列の連結リストの反転P0028

単語の順番を逆にする

英小文字と数字からなる単語が空白で区切られた一行が与えられる。
単語の間の空白は一つ以上のことがあり、行の前後に空白があることもある。
単語の順番を逆にし、単語の間にちょうど一つの空白を置いて一行で出力せよ。
単語の中の文字の順番はそのままにする。
行の前後には空白を書かない。

入力
行の長さ 1〜1,000、単語は 1 個以上
出力
逆順の単語、空白一つで区切る
例 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.つなぐ(" "));