2014-12-04 134 views
4

给定两个字符串base和remove,返回基本字符串的一个版本,其中删除字符串的所有实例都已被删除(不区分大小写)。您可能会认为删除字符串的长度为1或更多。只删除不重叠的实例,所以用“xxx”删除“xx”留下“x”。如何删除部分字符串

withoutString("Hello there", "llo") → "He there" 
withoutString("Hello there", "e") → "Hllo thr" 
withoutString("Hello there", "x") → "Hello there" 

为什么我不能使用此代码:

public String withoutString(String base, String remove) 
{ 
    base.replace(remove, ""); 
    return base; 
} 
+7

我没有得到,为什么人们投票了这个问题..:P – 2014-12-04 12:37:50

回答

8

base.replace不改变原有String例如,由于String是不可变的类。因此,您必须返回replace的输出,这是一个新的String

 public String withoutString(String base, String remove) 
     { 
      return base.replace(remove,""); 
     } 
4

String#replace()返回一个新的字符串,不会改变它被调用的字符串,因为字符串是不可变的。在代码中使用此:

base = base.replace(remove, "")

0

更新您的代码:

public String withoutString(String base, String remove) { 
    //base.replace(remove,"");//<-- base is not updated, instead a new string is builded 
    return base.replace(remove,""); 
} 
0

尝试下面的代码

public String withoutString(String base, String remove) { 
      return base.replace(remove,""); 
     } 

对于输入:

base=Hello World 
remove=llo 

输出:

He World 

更多关于这种string操作参观this链接。

0

Apache Commons库已经实现了这个方法,你不需要再次写入。

代码:

return StringUtils.remove(base, remove);