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

如何在指定字符数后最近空格处截断文本行,保留完整单词

解决Java文本按指定长度在空格处截断(保留完整单词)的问题

原代码的问题在于直接按固定长度截取字符串,会将完整单词从中间拆分。要实现达到指定字符数后在最近空格处截断、保留完整单词的效果,可以按以下思路修改:

  1. 每次从当前起始位置开始,先确定截取的候选结束位置(当前位置+20,不超过字符串总长度)
  2. 在候选范围内从后往前查找最后一个空格的位置
  3. 如果找到空格,就截断到该位置;如果没找到(比如单个单词长度超过20),则直接按候选结束位置截断
  4. 更新下一次循环的起始位置为截断位置的下一个字符(跳过空格)

修改后的完整代码

// 已导入Scanner工具类
import java.util.Scanner;

public class TextWrap {
    public static void main(String[] args) {
        System.out.println("Please input a sentence: ");
        Scanner stringScanner = new Scanner(System.in);
        String input = stringScanner.nextLine();
        
        int maxLineLength = 20;
        int currentStart = 0;
        
        while (currentStart < input.length()) {
            // 计算候选的结束位置,不超过字符串总长度
            int end = Math.min(currentStart + maxLineLength, input.length());
            // 在[currentStart, end]范围内找最后一个空格
            int splitPos = input.lastIndexOf(' ', end - 1);
            
            if (splitPos != -1 && splitPos > currentStart) {
                // 找到有效空格,截断到该位置
                String line = input.substring(currentStart, splitPos);
                System.out.println(line);
                // 下一次从空格的下一个字符开始
                currentStart = splitPos + 1;
            } else {
                // 没找到空格,直接按候选长度截断(处理超长单词)
                String line = input.substring(currentStart, end);
                System.out.println(line);
                currentStart = end;
            }
        }
        stringScanner.close();
    }
}

测试效果

输入:

hello there, I am doing some coding!

输出:

hello there, I am   
doing some coding!

完全符合期望的截断效果,保证了每行的单词完整性,且每行字符数不超过20。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:33:32