{ }codelper
空白の除去P0057

行の前後の空白を取り除く

一行目に行数 n が与えられる。
続いて n 行の文章が与えられる。
行ごとに先頭と末尾の空白をすべて取り除き、結果を角かっこで囲んで "[結果]" のように一行に出力せよ。
空白とは半角スペース、タブ、そして行末の \r である(入力ファイルは Windows 式の行末 \r\n のこともある)。
文字の間の空白はそのまま残す。
空行や空白だけの行なら "[]" を出力する。

入力
1 ≤ n ≤ 100。
各行はスペース・タブと ASCII の記号・英字・数字からなり、行末の文字を除いて長さ 0〜300
出力
n 行、行ごとに [整えた文章]
例 1 · stdin
3
  hello  
	world	
  keep   inner  
stdout
[hello]
[world]
[keep   inner]
main.py
入力(stdin)

実行すると、これらの行が順に input()・標準入力に渡されます(実行中に入力を求めません)。

$ 準備完了

コードを入力して解くにはパソコンで開いてください。モバイルでは問題と解答を見られます。

ほかの言語では?言語別の解答を見る · 8 言語の解答

前後の空白を取り除く:Python s.strip()、JS・TS s.trim()、Java s.trim()(コード 32 以下すべて)・s.strip()(Unicode の空白)、C# s.Trim()、Craykon s.空白除去()。
C と C++ には trim がないので、C は isspace で両端を狭め、C++ は find_first_not_of(" \t\r\n")/find_last_not_of で位置を探して substr します。
Windows の行末の落とし穴:一行読むときに \r を外してくれるかが言語ごとに違います。
Java の readLine・C# の ReadLine は \r\n をまとめて外し(Craykon のコンソールも \r を消します)、Python の input()・C の fgets・C++ の getline・JS の split("\n") は \r を残します。
なので C++ で取り除く文字の一覧に \r を入れ忘れると行末に \r が残り、その前のスペース・タブも消えません("hi\t\r" → "[hi\t\r]")。
ほかの落とし穴:Python の strip(" ") のようにスペースだけを指定するとタブと \r が残り、" ".join(s.split()) は内側の空白まで一つに縮めてしまいます。

Pythonmain.py · 3 行
n = int(input())for _ in range(n):    print("[" + input().strip() + "]")
JavaScriptmain.js · 4 行
const [n, ...lines] = require("fs").readFileSync(0, "utf8").split("\n");const out = [];for (let i = 0; i < Number(n); i++) out.push("[" + lines[i].trim() + "]");console.log(out.join("\n"));
TypeScriptmain.ts · 5 行
import { readFileSync } from "node:fs";const [n, ...lines]: string[] = readFileSync(0, "utf8").split("\n");const out: string[] = [];for (let i = 0; i < Number(n); i++) out.push("[" + lines[i].trim() + "]");console.log(out.join("\n"));
JavaMain.java · 14 行
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            out.append('[').append(br.readLine().strip()).append("]\n");        }        System.out.print(out);    }}
C#Main.cs · 16 行
using System;using System.Text; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var out_ = new StringBuilder();        for (int i = 0; i < n; i++)        {            out_.Append('[').Append(Console.ReadLine().Trim()).Append("]\n");        }        Console.Write(out_);    }}
C++main.cpp · 20 行
#include <iostream>#include <string> std::string trim(const std::string& s) {    const char* ws = " \t\r\n";    size_t a = s.find_first_not_of(ws);    if (a == std::string::npos) return "";    size_t b = s.find_last_not_of(ws);    return s.substr(a, b - a + 1);} int main() {    std::string line;    std::getline(std::cin, line);    int n = std::stoi(line);    for (int i = 0; i < n; i++) {        if (!std::getline(std::cin, line)) line = "";        std::cout << '[' << trim(line) << "]\n";    }}
Cmain.c · 19 行
#include <ctype.h>#include <stdio.h>#include <stdlib.h> int main(void) {    char line[512];    if (!fgets(line, sizeof line, stdin)) return 0;    int n = atoi(line);    for (int i = 0; i < n; i++) {        if (!fgets(line, sizeof line, stdin)) line[0] = '\0';        char *start = line;        while (*start && isspace((unsigned char)*start)) start++;   /* 빈칸·탭·\r·\n 모두 */        char *end = start;        while (*end) end++;        while (end > start && isspace((unsigned char)end[-1])) end--;        printf("[%.*s]\n", (int)(end - start), start);    }    return 0;}
Craykonmain.cray · 6 行
n = コンソール.行読み().数に();繰り返す (i = 0; i < n; i++){    line = コンソール.行読み();    コンソール.書く("[" + line.空白除去() + "]");}