첫 줄에 너비 w가 주어지고, 다음 줄부터 입력이 끝날 때까지 본문이 주어진다.
본문의 단어는 공백(빈칸, 탭, 줄 바꿈)이 아닌 글자가 이어진 덩이다.
단어를 차례로 줄에 담아 출력하라.
같은 줄의 단어 사이에는 빈칸을 하나만 두고, 줄 앞뒤에는 빈칸을 두지 않는다.
다음 단어를 빈칸 하나와 함께 붙였을 때 줄 길이가 w를 넘으면, 그 단어부터 새 줄에 쓴다. 꼭 w가 되면 같은 줄에 쓴다.
w보다 긴 단어는 앞에서부터 w글자씩 잘라 조각을 만들고(마지막 조각은 짧을 수 있다), 조각 하나하나를 단어처럼 다룬다.
본문의 줄 나눔과 빈 줄은 결과에 영향을 주지 않는다.
입력
1 ≤ w ≤ 80. 본문은 8,000글자 이하이고 단어가 하나 이상 있다. 단어는 출력 가능한 ASCII 글자로 이루어진다
출력
줄 바꿈을 마친 줄들
예시 1 · stdin
10
The quick brown fox
jumps over a supercalifragilistic dog.
stdout
The quick
brown fox
jumps over
a
supercalif
ragilistic
dog.
main.py
오류 목록00F8 ↓ · ⇧F8 ↑
입력(stdin)
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이
줄마다 단어를 목록에 모았다가 빈칸 하나로 이어(join) 쓰면 빈칸이 줄 끝에 남지 않아요: Python " ".join(line), JS·TS line.join(" "), Java String.join(" ", line), C# string.Join(" ", line). 넘는지 물을 때는 지금 길이 + 1 + 단어 길이 > w예요. >=로 쓰면 꼭 w인 줄도 한 칸 일찍 바꿔요. 단어 나누기는 JS split(" ")이 함정이에요. 빈칸이 겹친 곳에 빈 단어 ""를 만들고 탭은 나누지 않아요. trim().split(/\s+/), Python split(), C# Split((char[])null, RemoveEmptyEntries), C scanf("%s"), C++ >>는 공백 덩이를 한 번에 건너뛰어요. 본문은 여러 줄이니 첫 줄만 읽지 말고 입력 끝까지 읽어요. 긴 단어를 자를 때 Python word[i:i+w], JS slice, C++ substr(i, w)는 끝을 넘으면 거기서 멈춰요. C# Substring(i, w)와 Java substring(i, i + w)는 예외라서 Math.Min·Math.min으로 남은 길이를 넣어요. 긴 단어를 자르지 않거나, Python textwrap.wrap을 쓰면 안 돼요. textwrap은 긴 단어를 지금 줄의 남은 칸부터 채우기 때문에 이 문제의 규칙(조각은 w글자씩)과 달라요. 크레이콘 부분문자열(시작, 개수)도 C#처럼 끝을 넘으면 오류라서 수학.작은수(w, word.길이 - i)를 넘기고, 줄은 line.잇기(" ")로 이어요.
Pythonmain.py · 18 줄
import sysfirst, _, text = sys.stdin.read().partition("\n")w = int(first)pieces = []for word in text.split(): # 빈칸·탭·줄 바꿈이 몇 개든 한 번에 나눈다 for i in range(0, len(word), w): # 긴 단어는 w글자씩 자른다(슬라이스는 끝을 넘어도 괜찮다) pieces.append(word[i:i + w])lines, line, length = [], [], 0for p in pieces: if line and length + 1 + len(p) > w: # 빈칸 하나 + 조각이 w를 넘으면 새 줄 lines.append(" ".join(line)) line, length = [], 0 length += len(p) + (1 if line else 0) line.append(p)lines.append(" ".join(line))print("\n".join(lines))
JavaScriptmain.js · 22 줄
const input = require("fs").readFileSync(0, "utf8");const nl = input.indexOf("\n");const w = Number(input.slice(0, nl));const words = input.slice(nl + 1).trim().split(/\s+/);const pieces = [];for (const word of words) for (let i = 0; i < word.length; i += w) pieces.push(word.slice(i, i + w)); // slice는 끝을 넘어도 괜찮다const lines = [];let line = [];let length = 0;for (const p of pieces) { if (line.length > 0 && length + 1 + p.length > w) { lines.push(line.join(" ")); line = []; length = 0; } length += p.length + (line.length > 0 ? 1 : 0); line.push(p);}lines.push(line.join(" "));console.log(lines.join("\n"));
TypeScriptmain.ts · 23 줄
import { readFileSync } from "node:fs";const input: string = readFileSync(0, "utf8");const nl: number = input.indexOf("\n");const w: number = Number(input.slice(0, nl));const words: string[] = input.slice(nl + 1).trim().split(/\s+/);const pieces: string[] = [];for (const word of words) for (let i = 0; i < word.length; i += w) pieces.push(word.slice(i, i + w)); // slice는 끝을 넘어도 괜찮다const lines: string[] = [];let line: string[] = [];let length = 0;for (const p of pieces) { if (line.length > 0 && length + 1 + p.length > w) { lines.push(line.join(" ")); line = []; length = 0; } length += p.length + (line.length > 0 ? 1 : 0); line.push(p);}lines.push(line.join(" "));console.log(lines.join("\n"));
JavaMain.java · 35 줄
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int w = Integer.parseInt(in.readLine().trim()); List<String> pieces = new ArrayList<>(); String row; while ((row = in.readLine()) != null) { for (String word : row.trim().split("\\s+")) { if (word.isEmpty()) continue; // 빈 줄을 나누면 "" 하나가 나온다 for (int i = 0; i < word.length(); i += w) pieces.add(word.substring(i, Math.min(i + w, word.length()))); // 끝을 넘으면 예외 } } StringBuilder out = new StringBuilder(); List<String> line = new ArrayList<>(); int length = 0; for (String p : pieces) { if (!line.isEmpty() && length + 1 + p.length() > w) { out.append(String.join(" ", line)).append('\n'); line.clear(); length = 0; } length += p.length() + (line.isEmpty() ? 0 : 1); line.add(p); } out.append(String.join(" ", line)).append('\n'); System.out.print(out); }}
C#Main.cs · 35 줄
using System;using System.Collections.Generic;using System.Text;class Program{ static void Main() { int w = int.Parse(Console.ReadLine()); var pieces = new List<string>(); string row; while ((row = Console.ReadLine()) != null) { foreach (string word in row.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)) for (int i = 0; i < word.Length; i += w) pieces.Add(word.Substring(i, Math.Min(w, word.Length - i))); // 끝을 넘으면 예외 } var sb = new StringBuilder(); var line = new List<string>(); int length = 0; foreach (string p in pieces) { if (line.Count > 0 && length + 1 + p.Length > w) { sb.Append(string.Join(" ", line)).Append('\n'); line.Clear(); length = 0; } length += p.Length + (line.Count > 0 ? 1 : 0); line.Add(p); } sb.Append(string.Join(" ", line)).Append('\n'); Console.Write(sb); }}
C++main.cpp · 24 줄
#include <algorithm>#include <iostream>#include <string>#include <vector>int main() { std::size_t w; std::cin >> w; std::vector<std::string> pieces; std::string word; while (std::cin >> word) // >>는 공백을 건너뛰고 한 단어씩, 입력이 끝나면 거짓 for (std::size_t i = 0; i < word.size(); i += w) pieces.push_back(word.substr(i, w)); // substr는 끝에서 멈춘다 std::string out, line; for (const auto& p : pieces) { if (!line.empty() && line.size() + 1 + p.size() > w) { out += line + '\n'; line.clear(); } line += (line.empty() ? "" : " ") + p; } out += line + '\n'; std::cout << out;}
Cmain.c · 26 줄
#include <stdio.h>#include <string.h>int main(void) { int w, length = 0; /* length: 지금 줄에 쓴 글자 수(0이면 빈 줄) */ static char word[20001]; scanf("%d", &w); while (scanf("%20000s", word) == 1) { /* %s는 공백을 건너뛰고 한 단어씩 읽는다 */ int len = (int)strlen(word); for (int i = 0; i < len; i += w) { int k = len - i < w ? len - i : w; /* 이 조각의 길이 */ if (length > 0 && length + 1 + k > w) { putchar('\n'); length = 0; } if (length > 0) { putchar(' '); length++; } fwrite(word + i, 1, k, stdout); length += k; } } putchar('\n'); return 0;}
Craykonmain.cray · 33 줄
w = 콘솔.줄읽기().수로변환();pieces = [];row = 콘솔.줄읽기();동안 (row != 빈값){ 각각 (word 에서 row.나누기()) { // 긴 단어는 w글자씩. 부분문자열은 끝을 넘으면 오류라서 남은 길이와 작은 쪽을 쓴다 반복 (i = 0; i < word.길이; i += w) { pieces.넣기(word.부분문자열(i, 수학.작은수(w, word.길이 - i))); } } row = 콘솔.줄읽기();}line = [];length = 0;각각 (p 에서 pieces){ 만약 (line.개수 > 0 && length + 1 + p.길이 > w) { 콘솔.쓰기(line.잇기(" ")); line = []; length = 0; } 만약 (line.개수 > 0) { length += 1; } length += p.길이; line.넣기(p);}콘솔.쓰기(line.잇기(" "));