You need to enable JavaScript to run this app. 如何用Java实现字符串单空格分隔且每行不超过60字符格式化
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java实现字符串单空格分隔且每行不超过60字符格式化

问题排查与修复方案

现有代码的核心问题

  • 连续空格替换逻辑错误:当前正则[\n]{2,}仅匹配连续换行,无法处理连续空格,不符合第一步的需求
  • reformatLines方法语法错误:if判断后多余的分号导致判断逻辑失效,且该方法完全没有实现核心格式化逻辑
  • 循环判断条件错误:while循环判断的是原始字符串text的长度,但实际处理的是str变量,要么循环不执行要么进入死循环
  • 结果拼接逻辑缺失:循环结束后未将剩余未处理的字符串拼接到最终结果中,且最后没有输出或返回处理结果,运行后看不到任何效果

修正后的完整代码

public class TextFormatTool {
    public static String reformatLines(String text, int maxLineLength) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        // 第一步:所有连续空白替换为单个空格,同时去掉首尾多余空格
        String processedStr = text.replaceAll("\\s+", " ").trim();
        StringBuilder result = new StringBuilder();

        while (processedStr.length() > maxLineLength) {
            // 找到最大长度限制内的最后一个空格位置,作为换行分割点
            int splitIndex = processedStr.lastIndexOf(" ", maxLineLength);
            // 兼容极端情况:单个单词超过行长度限制时直接截断
            if (splitIndex == -1) {
                splitIndex = maxLineLength;
            }
            result.append(processedStr, 0, splitIndex).append("\n");
            // 剩余字符串去掉开头的空格后进入下一轮处理
            processedStr = processedStr.substring(splitIndex).trim();
        }
        // 拼接最后不足一行的内容
        result.append(processedStr);
        return result.toString();
    }

    public static void main(String[] args) {
        String originText = "Java    was      originally developed   by    James   Gosling at Sun Microsystems (which has since been acquired by Oracle) and released in 1995 as a core component of Sun Microsystems' Java platform.";
        String formattedText = reformatLines(originText, 60);
        System.out.println(formattedText);
    }
}

运行输出效果

Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle) and
released in 1995 as a core component of Sun Microsystems'
Java platform.

所有连续空格已替换为单个空格,每行长度均不超过60字符,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 07:24:04