我正在尝试解决codingbat中的“withoutString”练习,即从整个字符串中删除特定的子字符串。我确实解决了它,但现在我忘了为什么我添加了一些东西(显然需要)并且现在无法弄明白。
public String withoutString(String base, String remove) {
int length = remove.length();
String result = base; //unnecesssary, but i sometimes get confused with these things
int base_length = base.length();
for(int i = 0; i < base_length-length+1; i++){ //Part i cannot understand is here(explanation below)
if(result.toLowerCase().substring(i,length+i).equals(remove.toLowerCase())){
result = result.substring(0,i) + result.substring(length+i,base_length);
if(i+1 != base_length){ //in case that the needed substring is repeated one after another
i--;
}
}
base_length = result.length();
}
return result;
}
为什么“-length + 1”是必要的,如果没有它也不应该工作,因为我在循环中重新定义了base_length?
我得到的例外:
withoutString("Hello there", "llo") → "He there" (expected)
就是这样:
"Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 9 (line number:7)"
(顺便说一下,它适用于像withoutString(“Hello there”,“e”)→“Hllo thr”(预期)这样的东西。)
提前谢谢大家。
答案 0 :(得分:0)
对于您的示例withoutString("Hello there", "llo")
,base.length = 11,length = 3.您可以比较的最后一个位置是第一个e。之后,没有足够的字符可供匹配。