Word Wrap Greedy Line Filling

Wrap text greedily by splitting on whitespace, filling each line up to the width and starting a new line when the next word overflows.

RustCli Tooling

Code

rustsnippet
28 lines
// greedy word wrap: filling each line up to the width, one space between words
fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if !current.is_empty()
            && current.chars().count() + 1 + word.chars().count() > width
        {
            // mem::take swaps the finished line out and leaves an empty String
            lines.push(std::mem::take(&mut current));
        }
        if !current.is_empty() {
            current.push(' ');
        }
        current.push_str(word);
    }
    if !current.is_empty() {
        lines.push(current);
    }
    lines
}

fn main() {
    let text = "the quick brown fox jumps over the lazy dog";
    for line in wrap(text, 15) {
        println!("{line}");
    }
}

How it works

Word Wrap Greedy Line Filling keeps everything in the functions wrap and main.

A single loop drives the file — for word in text.split_whitespace().

Using it

Signature: fn wrap(text: &str, width: usize) -> Vec<String>

The sequence wrap lives in main; running the file triggers it.

Interactive Tools for This Topic

FAQ

How do you run Word Wrap Greedy Line Filling?
The runtime alone is enough: execute the file as a complete program.