给定两个字符串base和remove,将返回base字符串的一个版本,其中remove字符串的所有实例都已被删除(不区分大小写)。
您可以假设删除字符串的长度为1或更长。只删除不重叠的实例,因此使用"xxx"删除"xx"会留下"x"。例如,
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"但是我在codingbat中的大多数测试用例都失败了。有谁能帮帮我吗?
public String withoutString(String base, String remove) {
String result = "";
for(int i = 0; i < base.length() - remove.length(); i++){
if(!(base.substring(i, i + remove.length()).equalsIgnoreCase(remove))){
result += base.substring(i, i + 1);
}
else{
i = i + remove.length();
}
}
return result;
}

发布于 2020-07-31 18:28:24
以下是解决此问题的另一种方法:
public String withoutString(String base, String remove) {
return base.replaceAll("(?i)" + remove, "");
}https://stackoverflow.com/questions/32128664
复制相似问题