← 中文资源

简体中文版本

把单词按固定宽度折行

用贪心算法逐词填行:当前行放得下就接着追加,放不下就断到下一行,最终每行都不超过指定宽度,适合终端输出、日志摘要与纯文本排版场景。

阅读英文原文

实现说明

活动部件是类 WordWrap和函数 wrap、main。 重复被限制在 for (String word : text.split("\\s+")) 里——其余代码按顺序各跑一遍。

使用要点

  • 执行文件,main 会按顺序走完 wrap。

常见问题

「把单词按固定宽度折行」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

主签名形如 static List<String> wrap(String text, int width)

核心语句

String text = "The quick brown fox jumps over the lazy dog again and again";
StringBuilder line = new StringBuilder();
List<String> lines = new ArrayList<>();

代码示例

import java.util.ArrayList;
import java.util.List;

public class WordWrap {

    // greedy wrap: fill each line up to the width limit, then break
    static List<String> wrap(String text, int width) {
        List<String> lines = new ArrayList<>();
        StringBuilder line = new StringBuilder();
        for (String word : text.split("\\s+")) {
            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 = new StringBuilder(word);
            }
        }
        if (line.length() > 0) {
            lines.add(line.toString());
        }
        return lines;
    }

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog again and again";
        for (String line : wrap(text, 20)) {
            System.out.println("|" + line + "|");
        }
    }
}