Taskcore
Wrap text to a width
Also called word wrap, line wrap, wrap a paragraph, fill a paragraph, line breaking, greedy word wrap, textwrap, break text into lines, wrap at column, fold text.
Break a text into lines of at most a given width with the greedy method: put as many words as fit on a line, then start the next one. A word longer than the width gets a line of its own.
- Evidence
- Code in 10 languages
Task
Break a text into lines that are at most width characters long, for a terminal, a commit message, a comment or a plain text email. The Rosetta Code task Word wrap asks to "wrap a paragraph of text in a simple way in your language"1, with a function from the standard library if there is one, and otherwise with the "minimum length greedy algorithm"1.
The function wrap(text, width) returns the list of lines:
- Split the text into words at runs of white space: spaces, tabs and newlines.
- Put a word on the current line if the line stays at most
widthcharacters long, with one space between two words. - Otherwise, start a new line with the word.
- A word longer than
widthis not cut. It is a line of its own.
For example, wrap("The quick brown fox jumps over the lazy dog", 10) is ["The quick", "brown fox", "jumps over", "the lazy", "dog"]. An empty text, or a text with only white space, gives no lines.
Wikipedia says that "Word wrapping is an optimization problem"2. The greedy method "puts as many words on a line as possible, then moving on to the next line to do the same until there are no more words left to place"2. It "always uses the minimum possible number of lines but may lead to lines of widely varying lengths"2. A typesetting system such as TeX looks at the whole paragraph to make the lines more even, but the greedy method is the usual one for plain text.
Solutions
Python has the module textwrap. In the other languages of this site, the standard library has no function that wraps text, so the solution is a loop of about 15 lines.
| Language | Split into words | Wrap |
|---|---|---|
| Python | text.split() |
textwrap.wrap(text, width, break_long_words=False, break_on_hyphens=False), or a loop |
| JavaScript, TypeScript | text.split(/\s+/).filter(Boolean) |
a loop |
| Java | text.trim().split("\\s+") |
a loop with a StringBuilder |
| C# | text.Split(separators, StringSplitOptions.RemoveEmptyEntries) |
a loop with a StringBuilder |
| Go | strings.Fields(text) |
a loop |
| Rust | text.split_whitespace() |
a loop |
| C | a scan with isspace |
a loop that writes into a buffer |
| C++ | std::istringstream and >> |
a loop |
| Bash | read -r -d '' -a words |
a loop |
- Python.
textwrap.wrap"Wraps the single paragraph in text (a string) so every line is at most width characters long"3. By default it cuts a long word. Withbreak_long_words=False, "long words will not be broken, and some lines may be longer than width. (Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.)"3 The optionbreak_on_hyphens=Falsestops it from breaking a line after a hyphen in a word. - The loop. The other solutions keep the current line. For each word, if the line is empty, the line becomes the word. If the length of the line, plus 1 for the space, plus the length of the word is at most
width, the word goes on the line. Otherwise, the line goes into the result and the word starts a new line. At the end, a line that is not empty goes into the result. - C. The solution writes the lines into a buffer from the caller, with a newline after each line, and returns the count of lines.
- Bash.
read -r -d '' -a wordssplits the whole text, with its newlines, into an array.readreturns 1 at the end of the input, so the solution adds|| true. The function prints one line for each line of the result.
The Python loop, and textwrap for the same long word:
import textwrap
def wrap(text, width):
lines = []
line = ""
for word in text.split():
if not line:
line = word
elif len(line) + 1 + len(word) <= width:
line += " " + word
else:
lines.append(line)
line = word
if line:
lines.append(line)
return lines
for line in wrap("The quick brown fox jumps over the lazy dog", 10):
print(f"|{line:<10}|")
print(wrap("a supercalifragilistic word", 10))
print(textwrap.wrap("a supercalifragilistic word", 10))
print(textwrap.wrap("a supercalifragilistic word", 10, break_long_words=False))
|The quick |
|brown fox |
|jumps over|
|the lazy |
|dog |
['a', 'supercalifragilistic', 'word']
['a supercal', 'ifragilist', 'ic word']
['a', 'supercalifragilistic', 'word']
With the default options, textwrap cuts the long word to fill the lines.
Edge cases
- Empty text. No words, so no lines. The result is an empty list, not a list with one empty line.
- Only white space. The same as empty text.
- A text that fits. One line:
wrap("short text", 20)is["short text"]. - A line of exactly
widthcharacters. It is allowed:wrap("ab cd ef", 5)is["ab cd", "ef"]. The test is "at most", not "less than". - A word longer than
width. It is a line of its own, and that line is longer thanwidth. To cut it, the program must choose where, for example with a hyphen. - Runs of white space. Tabs, newlines and many spaces count as one break:
wrap("one two\tthree\nfour", 9)is["one two", "three", "four"]. - Width 1. Each word is a line.
Pitfalls
- An off by one in the test. The space between two words also takes a column. A loop that adds only the length of the word makes lines that are 1 character too long:
This code runs but gives a wrong answer on purpose.
function wrap(text, width) {
const lines = [];
let line = "";
for (const word of text.split(/\s+/).filter(Boolean)) {
if (line && line.length + word.length > width) {
lines.push(line);
line = word;
} else {
line = line ? line + " " + word : word;
}
}
if (line) lines.push(line);
return lines;
}
const lines = wrap("abc de fg", 5);
console.log(JSON.stringify(lines), lines.map((l) => l.length));
["abc de","fg"] [ 6, 2 ]
The test must be line.length + 1 + word.length > width.
- Characters are not columns. The contract uses ASCII. With other text, the length of a string is not its width on the screen: a letter with an accent can be 2 code points, and a Chinese character takes 2 columns on a terminal.
- The text keeps its spaces in
textwrap.textwrapkeeps the spaces between two words on one line, sotextwrap.wrap("one two", 9)is['one two']. The loop of this task puts one space between two words. - Paragraphs. The function wraps one paragraph. To keep the paragraphs of a text, split the text at the empty lines first, and wrap each paragraph.
- Words with a hyphen. By default,
textwrapcan break a line after a hyphen. The loop of this task does not break a word.
Related tasks
- Pad a string: pad each line to the width, to align the text on the right or in a box.
- Print formatted output: columns of a fixed width.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-text-to-a-width/.
def wrap(text: str, width: int) -> list[str]:
"""Return the lines of text, each at most width characters long, with
the greedy method. A word longer than width is a line of its own."""
lines: list[str] = []
line = ""
for word in text.split():
if not line:
line = word
elif len(line) + 1 + len(word) <= width:
line += " " + word
else:
lines.append(line)
line = word
if line:
lines.append(line)
return lines
if __name__ == "__main__":
print("\n".join(wrap("The quick brown fox jumps over the lazy dog", 10)))
test_wrap.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-text-to-a-width/.
import textwrap
import pytest
from wrap import wrap
CASES = [
("fox-ten", "The quick brown fox jumps over the lazy dog", 10, ["The quick", "brown fox", "jumps over", "the lazy", "dog"]),
("fox-twenty", "The quick brown fox jumps over the lazy dog", 20, ["The quick brown fox", "jumps over the lazy", "dog"]),
("sentence", "Wrap text to a width with a greedy loop.", 15, ["Wrap text to a", "width with a", "greedy loop."]),
("empty", "", 10, []),
("only-spaces", " ", 5, []),
("fits", "short text", 20, ["short text"]),
("exact-fit", "abcde fghij", 5, ["abcde", "fghij"]),
("long-word", "a supercalifragilistic word", 10, ["a", "supercalifragilistic", "word"]),
("many-spaces", "one two\tthree\nfour", 9, ["one two", "three", "four"]),
("width-one", "a b c", 1, ["a", "b", "c"]),
("line-exact", "ab cd ef", 5, ["ab cd", "ef"]),
]
@pytest.mark.parametrize(("name", "text", "width", "want"), CASES, ids=[c[0] for c in CASES])
def test_wrap(name, text, width, want):
assert wrap(text, width) == want
@pytest.mark.parametrize(("name", "text", "width", "want"), CASES, ids=[c[0] for c in CASES])
def test_same_as_textwrap_for_single_spaces(name, text, width, want):
single = " ".join(text.split())
assert wrap(text, width) == textwrap.wrap(single, width, break_long_words=False, break_on_hyphens=False)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
#ifndef WRAP_HPP
#define WRAP_HPP
#include <cstddef>
#include <sstream>
#include <string>
#include <vector>
// Returns the lines of text, each at most width characters long, with the
// greedy method. A word longer than width is a line of its own.
inline std::vector<std::string> wrap(const std::string& text, std::size_t width) {
std::vector<std::string> lines;
std::istringstream in(text);
std::string line;
std::string word;
while (in >> word) {
if (line.empty()) {
line = word;
} else if (line.size() + 1 + word.size() <= width) {
line += ' ';
line += word;
} else {
lines.push_back(line);
line = word;
}
}
if (!line.empty()) {
lines.push_back(line);
}
return lines;
}
#endif
test_wrap.cpp 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
#include <cstddef>
#include <cstdio>
#include <string>
#include <vector>
#include "wrap.hpp"
namespace {
struct test_case {
const char* name;
const char* text;
std::size_t width;
std::vector<std::string> want;
};
const test_case cases[] = {
{"fox-ten", "The quick brown fox jumps over the lazy dog", 10, {"The quick", "brown fox", "jumps over", "the lazy", "dog"}},
{"fox-twenty", "The quick brown fox jumps over the lazy dog", 20, {"The quick brown fox", "jumps over the lazy", "dog"}},
{"sentence", "Wrap text to a width with a greedy loop.", 15, {"Wrap text to a", "width with a", "greedy loop."}},
{"empty", "", 10, {}},
{"only-spaces", " ", 5, {}},
{"fits", "short text", 20, {"short text"}},
{"exact-fit", "abcde fghij", 5, {"abcde", "fghij"}},
{"long-word", "a supercalifragilistic word", 10, {"a", "supercalifragilistic", "word"}},
{"many-spaces", "one two\tthree\nfour", 9, {"one two", "three", "four"}},
{"width-one", "a b c", 1, {"a", "b", "c"}},
{"line-exact", "ab cd ef", 5, {"ab cd", "ef"}},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
if (wrap(c.text, c.width) != c.want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
import java.util.ArrayList;
import java.util.List;
/** Greedy word wrap. */
public final class Wrap {
private Wrap() {}
/**
* Returns the lines of text, each at most width characters long, with the
* greedy method. A word longer than width is a line of its own.
*/
public static List<String> wrap(String text, int width) {
List<String> lines = new ArrayList<>();
StringBuilder line = new StringBuilder();
for (String word : text.strip().split("\\s+")) {
if (word.isEmpty()) {
continue;
}
if (line.isEmpty()) {
line.append(word);
} else if (line.length() + 1 + word.length() <= width) {
line.append(' ').append(word);
} else {
lines.add(line.toString());
line.setLength(0);
line.append(word);
}
}
if (!line.isEmpty()) {
lines.add(line.toString());
}
return lines;
}
public static void main(String[] args) {
wrap("The quick brown fox jumps over the lazy dog", 10).forEach(System.out::println);
}
}
WrapTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class WrapTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("fox-ten", "The quick brown fox jumps over the lazy dog", 10, List.of("The quick", "brown fox", "jumps over", "the lazy", "dog")),
Arguments.of("fox-twenty", "The quick brown fox jumps over the lazy dog", 20, List.of("The quick brown fox", "jumps over the lazy", "dog")),
Arguments.of("sentence", "Wrap text to a width with a greedy loop.", 15, List.of("Wrap text to a", "width with a", "greedy loop.")),
Arguments.of("empty", "", 10, List.of()),
Arguments.of("only-spaces", " ", 5, List.of()),
Arguments.of("fits", "short text", 20, List.of("short text")),
Arguments.of("exact-fit", "abcde fghij", 5, List.of("abcde", "fghij")),
Arguments.of("long-word", "a supercalifragilistic word", 10, List.of("a", "supercalifragilistic", "word")),
Arguments.of("many-spaces", "one two\tthree\nfour", 9, List.of("one two", "three", "four")),
Arguments.of("width-one", "a b c", 1, List.of("a", "b", "c")),
Arguments.of("line-exact", "ab cd ef", 5, List.of("ab cd", "ef"))
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void wrap(String name, String text, int width, List<String> want) {
assertEquals(want, Wrap.wrap(text, width));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
#include "wrap.h"
#include <ctype.h>
#include <string.h>
int wrap(const char *text, size_t width, char *out, size_t size) {
size_t used = 0;
size_t line_len = 0;
int lines = 0;
const char *p = text;
for (;;) {
while (*p != '\0' && isspace((unsigned char)*p)) {
p++;
}
if (*p == '\0') {
break;
}
const char *start = p;
while (*p != '\0' && !isspace((unsigned char)*p)) {
p++;
}
size_t len = (size_t)(p - start);
if (line_len > 0 && line_len + 1 + len <= width) {
if (used + 1 + len + 2 > size) {
return -1;
}
out[used++] = ' ';
line_len++;
} else {
if (line_len > 0) {
out[used++] = '\n';
}
if (used + len + 2 > size) {
return -1;
}
line_len = 0;
lines++;
}
memcpy(out + used, start, len);
used += len;
line_len += len;
}
if (lines > 0) {
out[used++] = '\n';
}
out[used] = '\0';
return lines;
}
wrap.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
#ifndef WRAP_H
#define WRAP_H
#include <stddef.h>
// Writes the lines of text into out, each followed by a newline, with the
// greedy method: each line is at most width characters long, and a word
// longer than width is a line of its own. Returns the count of lines, or -1
// if out is too small. out must hold strlen(text) + 2 bytes.
int wrap(const char *text, size_t width, char *out, size_t size);
#endif
test_wrap.c 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
#include "wrap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
const char *text;
size_t width;
int count;
const char *want;
};
static const struct test_case cases[] = {
{"fox-ten", "The quick brown fox jumps over the lazy dog", 10, 5, "The quick\nbrown fox\njumps over\nthe lazy\ndog\n"},
{"fox-twenty", "The quick brown fox jumps over the lazy dog", 20, 3, "The quick brown fox\njumps over the lazy\ndog\n"},
{"sentence", "Wrap text to a width with a greedy loop.", 15, 3, "Wrap text to a\nwidth with a\ngreedy loop.\n"},
{"empty", "", 10, 0, ""},
{"only-spaces", " ", 5, 0, ""},
{"fits", "short text", 20, 1, "short text\n"},
{"exact-fit", "abcde fghij", 5, 2, "abcde\nfghij\n"},
{"long-word", "a supercalifragilistic word", 10, 3, "a\nsupercalifragilistic\nword\n"},
{"many-spaces", "one two\tthree\nfour", 9, 3, "one two\nthree\nfour\n"},
{"width-one", "a b c", 1, 3, "a\nb\nc\n"},
{"line-exact", "ab cd ef", 5, 2, "ab cd\nef\n"},
};
int main(void) {
int failures = 0;
char buf[128];
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
int n = wrap(c->text, c->width, buf, sizeof buf);
if (n != c->count || strcmp(buf, c->want) != 0) {
printf("FAIL %s: got %d \"%s\"\n", c->name, n, buf);
failures++;
}
}
char small[8];
if (wrap("The quick brown fox", 10, small, sizeof small) != -1) {
printf("FAIL small buffer\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>Greedy word wrap.</summary>
public static class Wrap
{
private static readonly char[] Spaces = { ' ', '\t', '\r', '\n' };
/// <summary>
/// Returns the lines of text, each at most width characters long, with
/// the greedy method. A word longer than width is a line of its own.
/// </summary>
public static List<string> Lines(string text, int width)
{
var lines = new List<string>();
var line = new StringBuilder();
foreach (var word in text.Split(Spaces, StringSplitOptions.RemoveEmptyEntries))
{
if (line.Length == 0)
{
line.Append(word);
}
else if (line.Length + 1 + word.Length <= width)
{
line.Append(' ').Append(word);
}
else
{
lines.Add(line.ToString());
line.Clear().Append(word);
}
}
if (line.Length > 0)
{
lines.Add(line.ToString());
}
return lines;
}
}
WrapTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
using System;
using Xunit;
public sealed class WrapTests
{
public static TheoryData<string, string, int, string[]> Cases => new()
{
{ "fox-ten", "The quick brown fox jumps over the lazy dog", 10, new string[] { "The quick", "brown fox", "jumps over", "the lazy", "dog" } },
{ "fox-twenty", "The quick brown fox jumps over the lazy dog", 20, new string[] { "The quick brown fox", "jumps over the lazy", "dog" } },
{ "sentence", "Wrap text to a width with a greedy loop.", 15, new string[] { "Wrap text to a", "width with a", "greedy loop." } },
{ "empty", "", 10, Array.Empty<string>() },
{ "only-spaces", " ", 5, Array.Empty<string>() },
{ "fits", "short text", 20, new string[] { "short text" } },
{ "exact-fit", "abcde fghij", 5, new string[] { "abcde", "fghij" } },
{ "long-word", "a supercalifragilistic word", 10, new string[] { "a", "supercalifragilistic", "word" } },
{ "many-spaces", "one two\tthree\nfour", 9, new string[] { "one two", "three", "four" } },
{ "width-one", "a b c", 1, new string[] { "a", "b", "c" } },
{ "line-exact", "ab cd ef", 5, new string[] { "ab cd", "ef" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Lines(string name, string text, int width, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Wrap.Lines(text, width));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
/**
* Returns the lines of text, each at most width characters long, with the
* greedy method. A word longer than width is a line of its own.
*/
export function wrap(text, width) {
const lines = [];
let line = "";
for (const word of text.split(/\s+/).filter(Boolean)) {
if (line === "") {
line = word;
} else if (line.length + 1 + word.length <= width) {
line += " " + word;
} else {
lines.push(line);
line = word;
}
}
if (line !== "") {
lines.push(line);
}
return lines;
}
wrap.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { wrap } from "./wrap.js";
const cases = [
["fox-ten", "The quick brown fox jumps over the lazy dog", 10, ["The quick", "brown fox", "jumps over", "the lazy", "dog"]],
["fox-twenty", "The quick brown fox jumps over the lazy dog", 20, ["The quick brown fox", "jumps over the lazy", "dog"]],
["sentence", "Wrap text to a width with a greedy loop.", 15, ["Wrap text to a", "width with a", "greedy loop."]],
["empty", "", 10, []],
["only-spaces", " ", 5, []],
["fits", "short text", 20, ["short text"]],
["exact-fit", "abcde fghij", 5, ["abcde", "fghij"]],
["long-word", "a supercalifragilistic word", 10, ["a", "supercalifragilistic", "word"]],
["many-spaces", "one two\tthree\nfour", 9, ["one two", "three", "four"]],
["width-one", "a b c", 1, ["a", "b", "c"]],
["line-exact", "ab cd ef", 5, ["ab cd", "ef"]],
];
for (const [name, text, width, want] of cases) {
test(name, () => {
assert.deepEqual(wrap(text, width), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
/**
* Returns the lines of text, each at most width characters long, with the
* greedy method. A word longer than width is a line of its own.
*/
export function wrap(text: string, width: number): string[] {
const lines: string[] = [];
let line = "";
for (const word of text.split(/\s+/).filter(Boolean)) {
if (line === "") {
line = word;
} else if (line.length + 1 + word.length <= width) {
line += " " + word;
} else {
lines.push(line);
line = word;
}
}
if (line !== "") {
lines.push(line);
}
return lines;
}
wrap.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { wrap } from "./wrap.ts";
const cases: [string, string, number, string[]][] = [
["fox-ten", "The quick brown fox jumps over the lazy dog", 10, ["The quick", "brown fox", "jumps over", "the lazy", "dog"]],
["fox-twenty", "The quick brown fox jumps over the lazy dog", 20, ["The quick brown fox", "jumps over the lazy", "dog"]],
["sentence", "Wrap text to a width with a greedy loop.", 15, ["Wrap text to a", "width with a", "greedy loop."]],
["empty", "", 10, []],
["only-spaces", " ", 5, []],
["fits", "short text", 20, ["short text"]],
["exact-fit", "abcde fghij", 5, ["abcde", "fghij"]],
["long-word", "a supercalifragilistic word", 10, ["a", "supercalifragilistic", "word"]],
["many-spaces", "one two\tthree\nfour", 9, ["one two", "three", "four"]],
["width-one", "a b c", 1, ["a", "b", "c"]],
["line-exact", "ab cd ef", 5, ["ab cd", "ef"]],
];
for (const [name, text, width, want] of cases) {
test(name, () => {
assert.deepEqual(wrap(text, width), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
// Package wrap breaks a text into lines with the greedy method.
package wrap
import "strings"
// Wrap returns the lines of text, each at most width bytes long, with the
// greedy method. A word longer than width is a line of its own.
func Wrap(text string, width int) []string {
var lines []string
line := ""
for _, word := range strings.Fields(text) {
switch {
case line == "":
line = word
case len(line)+1+len(word) <= width:
line += " " + word
default:
lines = append(lines, line)
line = word
}
}
if line != "" {
lines = append(lines, line)
}
return lines
}
wrap_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
package wrap
import (
"slices"
"testing"
)
var cases = []struct {
name string
text string
width int
want []string
}{
{"fox-ten", "The quick brown fox jumps over the lazy dog", 10, []string{"The quick", "brown fox", "jumps over", "the lazy", "dog"}},
{"fox-twenty", "The quick brown fox jumps over the lazy dog", 20, []string{"The quick brown fox", "jumps over the lazy", "dog"}},
{"sentence", "Wrap text to a width with a greedy loop.", 15, []string{"Wrap text to a", "width with a", "greedy loop."}},
{"empty", "", 10, []string{}},
{"only-spaces", " ", 5, []string{}},
{"fits", "short text", 20, []string{"short text"}},
{"exact-fit", "abcde fghij", 5, []string{"abcde", "fghij"}},
{"long-word", "a supercalifragilistic word", 10, []string{"a", "supercalifragilistic", "word"}},
{"many-spaces", "one two\tthree\nfour", 9, []string{"one two", "three", "four"}},
{"width-one", "a b c", 1, []string{"a", "b", "c"}},
{"line-exact", "ab cd ef", 5, []string{"ab cd", "ef"}},
}
func TestWrap(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := Wrap(c.text, c.width); !slices.Equal(got, c.want) {
t.Fatalf("Wrap(%q, %d) = %q, want %q", c.text, c.width, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
/// Returns the lines of text, each at most width bytes long, with the
/// greedy method. A word longer than width is a line of its own.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split_whitespace() {
if line.is_empty() {
line.push_str(word);
} else if line.len() + 1 + word.len() <= width {
line.push(' ');
line.push_str(word);
} else {
lines.push(std::mem::take(&mut line));
line.push_str(word);
}
}
if !line.is_empty() {
lines.push(line);
}
lines
}
tests/wrap_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/wrap-text-to-a-width/.
use algo_wrap_text_to_a_width::wrap;
const CASES: &[(&str, &str, usize, &[&str])] = &[
("fox-ten", "The quick brown fox jumps over the lazy dog", 10, &["The quick", "brown fox", "jumps over", "the lazy", "dog"]),
("fox-twenty", "The quick brown fox jumps over the lazy dog", 20, &["The quick brown fox", "jumps over the lazy", "dog"]),
("sentence", "Wrap text to a width with a greedy loop.", 15, &["Wrap text to a", "width with a", "greedy loop."]),
("empty", "", 10, &[]),
("only-spaces", " ", 5, &[]),
("fits", "short text", 20, &["short text"]),
("exact-fit", "abcde fghij", 5, &["abcde", "fghij"]),
("long-word", "a supercalifragilistic word", 10, &["a", "supercalifragilistic", "word"]),
("many-spaces", "one two\tthree\nfour", 9, &["one two", "three", "four"]),
("width-one", "a b c", 1, &["a", "b", "c"]),
("line-exact", "ab cd ef", 5, &["ab cd", "ef"]),
];
#[test]
fn cases() {
for &(name, text, width, want) in CASES {
assert_eq!(wrap(text, width), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-text-to-a-width/.
# wrap text width: print the lines of text, each at most width characters
# long, with the greedy method. A word longer than width is a line of its
# own. read -d '' reads the whole text, newlines included, and returns 1 at
# the end of the input.
wrap() {
local width=$2 line='' word
local -a words
read -r -d '' -a words <<<"$1" || true
for word in "${words[@]}"; do
if [[ -z $line ]]; then
line=$word
elif ((${#line} + 1 + ${#word} <= width)); then
line+=" $word"
else
printf '%s\n' "$line"
line=$word
fi
done
if [[ -n $line ]]; then
printf '%s\n' "$line"
fi
}
test_wrap.bats 63 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/wrap-text-to-a-width/.
setup() {
source "$BATS_TEST_DIRNAME/wrap.sh"
}
@test "fox-ten" {
run wrap 'The quick brown fox jumps over the lazy dog' 10
[ "$output" = $'The quick\nbrown fox\njumps over\nthe lazy\ndog' ]
}
@test "fox-twenty" {
run wrap 'The quick brown fox jumps over the lazy dog' 20
[ "$output" = $'The quick brown fox\njumps over the lazy\ndog' ]
}
@test "sentence" {
run wrap 'Wrap text to a width with a greedy loop.' 15
[ "$output" = $'Wrap text to a\nwidth with a\ngreedy loop.' ]
}
@test "empty" {
run wrap '' 10
[ "$output" = $'' ]
}
@test "only-spaces" {
run wrap ' ' 5
[ "$output" = $'' ]
}
@test "fits" {
run wrap 'short text' 20
[ "$output" = $'short text' ]
}
@test "exact-fit" {
run wrap 'abcde fghij' 5
[ "$output" = $'abcde\nfghij' ]
}
@test "long-word" {
run wrap 'a supercalifragilistic word' 10
[ "$output" = $'a\nsupercalifragilistic\nword' ]
}
@test "many-spaces" {
run wrap 'one two three
four' 9
[ "$output" = $'one two\nthree\nfour' ]
}
@test "width-one" {
run wrap 'a b c' 1
[ "$output" = $'a\nb\nc' ]
}
@test "line-exact" {
run wrap 'ab cd ef' 5
[ "$output" = $'ab cd\nef' ]
}
References
- Rosetta Code, Word wrap (task text, from acmeism/RosettaCodeData), task text
- Wrapping (text), Wikipedia, Algorithm; Minimum number of lines
- textwrap, Text wrapping and filling, Python documentation, textwrap.wrap; TextWrapper.break_long_words; TextWrapper.replace_whitespace
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag KBZ8FA Edit this page History Report an error Markdown