如何删除字符串的一部分

5
给定两个字符串,base和remove,返回一个版本的base字符串,其中删除了所有remove字符串的实例(不区分大小写)。您可以假设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 - Deepak Sharma
5个回答

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

欲了解更多关于此类 字符串 操作,可访问 this 链接。


0

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

代码:

 return StringUtils.remove(base, remove);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接