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.
Code
// 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.Text Wrap FormatterSoft-wrap paragraphs to a chosen column width for emails, commit messages, and terminal output, optionally breaking words longer than the width.
FAQ
- How do you run Word Wrap Greedy Line Filling?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.