{ }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.去空白() + "]");}