gpt4 book ai didi

java - while 循环内来自 stringbuilder 的 StringIndexOutOfBoundsException 错误

转载 作者:行者123 更新时间:2023-11-30 04:11:09 25 4
gpt4 key购买 nike

例如,分配是从字符串“I am Sam am I Sam”中删除字符“a”,这是我有的一段代码远:

public String removeLetters() {
String cleaned=sentence;
StringBuilder builder = new StringBuilder(cleaned);

while(cleaned.indexOf(lookFor) != -1) {
builder.deleteCharAt(cleaned.indexOf(lookFor));
}
return builder.toString();
}

当没有 while 循环时,此方法返回正常(尽管它只删除一个字符),但是当我使用 while 循环运行它时,我收到 OutOfBounds 错误。

最佳答案

更改此:

while(cleaned.indexOf(lookFor) != -1) {
builder.deleteCharAt(cleaned.indexOf(lookFor));
}

这样:

while(builder.indexOf(Character.toString(lookFor)) != -1) {
builder.deleteCharAt(builder.indexOf(Character.toString(lookFor)));
}

关于java - while 循环内来自 stringbuilder 的 StringIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571372/

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