You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java左对齐文本排版如何避免行尾单词被拆分换行

Java实现按最大行宽左对齐不拆分单词的修复方案

问题根因

原有代码的splitInputString方法采用固定长度硬切割的逻辑,未识别单词边界,因此会将完整单词拆分为两部分分布在相邻行,不符合需求。

修复逻辑

  1. 先将输入文本按空格拆分得到所有独立单词列表
  2. 逐单词拼接生成行:每次判断当前行拼接当前单词(含前置空格)后是否超过最大行宽
  3. 若超过则将当前行存入结果列表,以当前单词作为新行的开头
  4. 左对齐场景下,每行生成后用空格补全到最大行宽

注意事项

  • 原有输入代码中Arrays.toString(paragraphs)会将字符串数组转为带[]括号、元素间带, 分隔符的字符串,会引入多余字符。建议替换为String.join(" ", paragraphs)拼接读取到的段落内容。

修复后完整代码

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;

public class StringAlignUtils {
    private int maxChars;
    private String alignment;

    public StringAlignUtils(String alignmentType, int maxChars) {
        this.alignment = alignmentType;
        if (maxChars <= 0) {
            throw new IllegalArgumentException("maxChars必须为正整数。");
        }
        this.maxChars = maxChars;
    }

    public StringBuffer format(Object input, StringBuffer where, FieldPosition ignore) {
        String s = input.toString();
        List<String> lines = splitInputString(s);
        for (String line : lines) {
            switch (alignment) {
                case "L":
                    where.append(line);
                    // 左对齐补空格到最大行宽
                    pad(where, maxChars - line.length());
                    break;
            }
            where.append("\n");
        }
        return where;
    }

    protected final void pad(StringBuffer to, int howMany) {
        for (int i = 0; i < howMany; i++)
            to.append(' ');
    }

    String format(String s) {
        return format(s, new StringBuffer(), null).toString();
    }

    public Object parseObject(String source, ParsePosition pos) {
        return source;
    }

    private List<String> splitInputString(String str) {
        List<String> result = new ArrayList<>();
        if (str == null || str.trim().isEmpty()) {
            return result;
        }
        // 按空格拆分所有单词,过滤空字符串
        String[] words = str.trim().split("\\s+");
        StringBuilder currentLine = new StringBuilder();
        for (String word : words) {
            // 计算当前行加这个单词的长度:行首不用加空格,其他情况要加空格间隔
            int addedLength = currentLine.length() == 0 ? word.length() : word.length() + 1;
            if (currentLine.length() + addedLength > maxChars) {
                // 加了之后超行宽,把当前行存进结果,新行以这个单词开头
                result.add(currentLine.toString());
                currentLine.setLength(0);
                currentLine.append(word);
            } else {
                // 不超就拼上
                if (currentLine.length() > 0) {
                    currentLine.append(" ");
                }
                currentLine.append(word);
            }
        }
        // 最后剩下的一行也要加进去
        if (currentLine.length() > 0) {
            result.add(currentLine.toString());
        }
        return result;
    }
}

效果验证

最大行宽设为80时,修复后输出和预期完全一致,不会出现单词被拆分的情况:

  1. Many things went on at the Unseen University and, regrettably teaching had to be
  2. one of them. The faculty had long ago confronted this fact and had perfected various
  3. devices for avoiding it.

内容的提问来源于stack exchange,提问作者Zuha Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:18:00