← 中文资源

简体中文版本

贪心 word wrap 按宽度断行

按空白切词后贪心填行:下一词放不下就把当前行收走,mem::take 换出成品行并留下空串,最终输出每行都不超过指定宽度。

阅读英文原文

实现说明

贪心 word wrap 按宽度断行以函数 wrap、main为骨架。 for word in text.split_whitespace() 承担全部的逐项处理。

使用要点

  • main 按顺序串起 wrap;运行文件就会把这个流程跑一遍。

常见问题

「贪心 word wrap 按宽度断行」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

签名一览:fn wrap(text: &str, width: usize) -> Vec<String>

代码示例

// 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}");
    }
}