如何删除字符串的一部分

时间:2014-12-04 12:34:27

标签: java string

给定两个字符串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;
}

5 个答案:

答案 0 :(得分:8)

base.replace不会更改原始String实例,因为String是不可变类。因此,您必须返回replace的输出,这是一个新的String

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

答案 1 :(得分:4)

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

base = base.replace(remove, "")

答案 2 :(得分: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,"");
}

答案 3 :(得分:0)

尝试以下代码

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

输入:

base=Hello World   
remove=llo

输出

He World

有关此类string操作的详情,请访问this链接。

答案 4 :(得分:0)

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

代码:

 return StringUtils.remove(base, remove);