【问题标题】:how to remove a part of a string如何删除字符串的一部分
【发布时间】:2014-12-04 12:34:26
【问题描述】:

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

【问题讨论】:

  • 我没明白,为什么人们要投票给这个问题..:P

标签: java string


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    base = base.replace(remove, "")

    【讨论】:

      【解决方案3】:

      更新您的代码:

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

      【讨论】:

        【解决方案4】:

        试试下面的代码

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

        对于输入:

        base=Hello World   
        remove=llo
        

        输出:

        He World
        

        有关此类string 操作的更多信息,请访问this 链接。

        【讨论】:

          【解决方案5】:

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

          代码:

           return StringUtils.remove(base, remove);
          

          【讨论】: