如何实现文本按20字符就近空格截断,修复重复输出问题?
文本按指定宽度拆分问题排查与解决
问题描述
需要实现将输入文本按每行不超过20字符分割,分割点为最近的空格,确保每行仅含完整单词。现有Java代码运行后出现重复输出异常,当前输出与期望输出不符。
现有代码
System.out.println("Please input a word: "); Scanner stringScanner = new Scanner(System.in); String input = stringScanner.nextLine(); int numberOfCharacters = 20; for(int pos = numberOfCharacters; pos >= 0; pos --) { if(input.charAt(pos) == ' ') { System.out.println(input.substring(0, pos)); System.out.println(input.substring(pos+1,21)); } }
当前异常输出
Please input a word: Hello there, I am doing some coding, I need some help Hello there, I am doi Hello there, I am doi Hello there, I am doi Hello there, I am doi
期望输出
The output I want is: Hello there, I am doing some coding, I need some help
错误原因分析
- 循环逻辑错误:原代码从20位往前遍历所有空格,每找到一个空格就触发一次输出,导致所有符合条件的空格位置都生成拆分结果,产生重复内容。
- 未处理剩余文本:原代码仅处理前21个字符内的拆分,没有循环处理后续长文本,无法完成整个输入的分段。
- 硬编码截取长度:
substring(pos+1,21)固定截取到21位,没有根据剩余文本长度动态调整。
修正方案
重新设计循环逻辑:持续处理输入文本,每次找到当前文本中最接近20字符位置的空格,拆分后将剩余文本作为新的处理对象,直到文本全部处理完成。
修正后的代码
import java.util.Scanner; public class TextSplitter { public static void main(String[] args) { System.out.println("Please input a sentence: "); Scanner stringScanner = new Scanner(System.in); String input = stringScanner.nextLine(); stringScanner.close(); final int MAX_LINE_LENGTH = 20; int currentPos = 0; while (currentPos < input.length()) { // 计算当前行的最大结束位置 int endPos = Math.min(currentPos + MAX_LINE_LENGTH, input.length()); // 从endPos往前找最近的空格 while (endPos > currentPos && input.charAt(endPos - 1) != ' ') { endPos--; } // 处理单个单词超过20字符的情况,直接截断 if (endPos == currentPos) { endPos = Math.min(currentPos + MAX_LINE_LENGTH, input.length()); } // 输出当前行并去除首尾空格 System.out.println(input.substring(currentPos, endPos).trim()); // 更新当前位置,跳过后续空格 currentPos = endPos; while (currentPos < input.length() && input.charAt(currentPos) == ' ') { currentPos++; } } } }
代码说明
- 循环处理全文本:通过
while循环持续处理剩余未分段的文本,直到全部处理完毕。 - 动态定位拆分点:从最大允许长度位置往前遍历,找到最近的空格作为拆分点,保证单词完整性。
- 兼容超长单词:若单个单词超过20字符,直接截断到20位,避免死循环。
- 跳过冗余空格:拆分后跳过起始位置的空格,避免输出空行或前置空格。
测试结果
输入Hello there, I am doing some coding, I need some help,输出与期望一致:
Hello there, I am doing some coding, I need some help
内容的提问来源于stack exchange,提问作者Nick Slack
相关产品推荐
相关产品推荐

