gpt4 book ai didi

java - 使用字符串生成器时字符串索引超出范围

转载 作者:行者123 更新时间:2023-12-01 22:16:47 25 4
gpt4 key购买 nike

所以我确实遇到了这种类型的错误:

java.lang.StringIndexOutOfBoundsException: String index out of range: 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 不在范围内。

最佳答案

477 是因为您删除了其余索引。只需在删除索引之前检查一下即可,例如

if (textSb.charAt(i) == ' ' && (i+1<textLength)){
textSb.deleteCharAt(i+1);
i--;
}

关于java - 使用字符串生成器时字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com