【发布时间】:2019-10-30 07:23:51
【问题描述】:
所以我确实得到了这种类型的错误:
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围: 447
每次我运行这段代码时:
String text = "What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
StringBuilder textSb = new StringBuilder(text);
int textLength = textSb.length();
System.out.println(textLength);
for(int i = 3; i< textLength; i += 4){
if (textSb.charAt(i) == ' '){
textSb.deleteCharAt(i+1);
i--;
}else{
textSb.deleteCharAt(i);
i--;
}
好的。所以它想做什么。每次循环第四个字符时,我都会尝试删除,如果是空格,我会删除空格后的第二个字符。我尝试“i--”,因为文本变小,每次只有一个字符,这意味着我的索引将无法正常工作,因为我会不断删除这些字符。
主要问题是那个错误。考虑到我的字符串中有大约 597 个字符,怎么可能 447 不在范围内。
【问题讨论】:
-
你永远不会重新计算
textLength,但你会删除字符...... -
@ElliottFrisch 我尝试制作 textlength++ 并且是同样的错误。 for 是否只获取它的文本长度一次?
-
这个练习有什么意义?您的预期输出是什么样的?
-
只需将for循环修改为
for(int i = 3; i< textSb.length(); i += 4),结果应该类似于Wha is orm Isum Loem psu is...。 -
您可能需要先检查
i+1是否小于textLength,然后再执行textSb.deleteCharAt(i+1);。您可以在现有的if条件本身中添加检查:if (textSb.charAt(i) == ' ' && i+1<textLength)。另一个问题是,当您删除 Elliott 提到的角色时,您需要重新分配textLength的值。在每个删除语句后添加textLength = textSb.length();。
标签: java stringbuilder