{ }codelper
substringsjoining stringsP0104

Wrap to a width

The first line gives the width w, and the text follows from the next line until the end of input. A word in the text is a run of characters that are not whitespace (spaces, tabs or line breaks). Put the words onto lines in order and print the lines. Words on the same line are separated by exactly one space, with no spaces at the start or end of a line. If adding the next word with one space would make the line longer than w, start a new line with that word.
If it makes the line exactly w, it stays on the same line. A word longer than w is cut from the front into pieces of w characters (the last piece may be shorter), and each piece is handled like a word. The line breaks and blank lines in the text do not affect the result.

Input
1 ≤ w ≤ 80.
The text has at most 8,000 characters and contains at least one word.
Words consist of printable ASCII characters
Output
the wrapped lines
Example 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
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Collect each line's words in a list and join them with one space, and no space is left at the end of a line: Python " ".join(line), JS/TS line.join(" "), Java String.join(" ", line), C# string.Join(" ", line).
The overflow test is current length + 1 + word length > w; with >= a line that is exactly w breaks one word early.
For splitting words, JS split(" ") is the trap: it makes an empty word "" where spaces repeat and does not split on tabs.
trim().split(/\s+/), Python split(), C# Split((char[])null, RemoveEmptyEntries), C scanf("%s") and C++ >> skip any run of whitespace.
The text spans several lines, so read to the end of input, not just the first line.
When cutting long words, Python word[i:i+w], JS slice and C++ substr(i, w) stop at the end.
C# Substring(i, w) and Java substring(i, i + w) throw, so pass the remaining length with Math.Min/Math.min.
Do not leave long words uncut, and do not use Python textwrap.wrap: it fills the rest of the current line with the start of a long word, which differs from this problem's rule (pieces of w characters).
Craykon Substring(start, count) also fails past the end, like C#, so pass Mathf.Min(w, word.Length - i), and join a line with line.Join(" ").

Pythonmain.py · 18 lines
import sys first, _, 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 lines
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 lines
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 lines
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 lines
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 lines
#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 lines
#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 lines
w = Console.ReadLine().ToNumber();pieces = [];row = Console.ReadLine();while (row != null){    foreach (word in row.Split())    {        // 긴 단어는 w글자씩. 부분문자열은 끝을 넘으면 오류라서 남은 길이와 작은 쪽을 쓴다        for (i = 0; i < word.Length; i += w)        {            pieces.Add(word.Substring(i, Mathf.Min(w, word.Length - i)));        }    }    row = Console.ReadLine();}line = [];length = 0;foreach (p in pieces){    if (line.Count > 0 && length + 1 + p.Length > w)    {        Console.WriteLine(line.Join(" "));        line = [];        length = 0;    }    if (line.Count > 0)    {        length += 1;    }    length += p.Length;    line.Add(p);}Console.WriteLine(line.Join(" "));