Java字符串按整词拆分至20字符内的代码疑问与报错解决
字符串按指定宽度拆分(每行≤20字符)的问题解决
异常原因分析
java.lang.StringIndexOutOfBoundsException通常是这两种情况触发的:
- 计算结束位置时直接取
startPos + 20,没考虑剩余字符串长度不足20的情况,导致索引超出字符串范围 - 查找空格分割点时,没做边界判断,比如剩余部分是一个超长单词,找不到空格就直接用非法索引
伪代码里「startPos设为endPos+1」的逻辑解释
这一步就是用来定位下一行的起始位置:
- 当找到当前行的结束位置
endPos(一般是空格的索引),当前行的内容是从startPos到endPos-1(空格不需要留在当前行末尾) - 下一行就得跳过这个空格,从
endPos+1开始,既避免下一行开头带空格,也保证从下一个有效字符开始处理
修复后的Java代码实现
public class StringSplitter { public static void splitByWidth(String input, int maxWidth) { int startPos = 0; int length = input.length(); while (startPos < length) { // 先算出当前行最大可能的结束位置,避免超出字符串长度 int endPos = Math.min(startPos + maxWidth, length); // 还没到字符串末尾的话,往前找最近的空格作为分割点 if (endPos < length) { endPos = input.lastIndexOf(' ', endPos - 1); // 找不到空格(比如单个单词超过20字符),直接截断到允许的最大长度 if (endPos == -1) { endPos = startPos + maxWidth; endPos = Math.min(endPos, length); } } // 输出当前行 System.out.println(input.substring(startPos, endPos)); // 更新下一行的起始位置 startPos = endPos + 1; // 跳过连续空格,避免输出空行或开头带空格的行 while (startPos < length && input.charAt(startPos) == ' ') { startPos++; } } } public static void main(String[] args) { String testInput = "Hello world this is a long string that needs to be split into lines of twenty characters"; splitByWidth(testInput, 20); } }
代码关键点说明
- 边界防护:用
Math.min限制endPos的最大值,从根源避免索引越界 - 空格定位:从最大允许位置的前一位往前找空格,保证拆分在最近的单词间隙
- 超长单词兼容:找不到空格时直接截断到指定宽度,避免卡死或异常
- 空格过滤:更新
startPos后跳过连续空格,输出更整洁
内容的提问来源于stack exchange,提问作者Nick Slack
相关产品推荐
相关产品推荐

