[英]how to remove a part of a string
Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). 给定两个字符串base和remove,返回基本字符串的一个版本,其中删除了删除字符串的所有实例(不区分大小写)。 You may assume that the remove string is of length 1 or more.
您可以假设删除字符串的长度为1或更长。 Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".
仅删除不重叠的实例,因此使用“xxx”删除“xx”会留下“x”。
withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"
Why can't I use this code: 为什么我不能使用这段代码:
public String withoutString(String base, String remove)
{
base.replace(remove, "");
return base;
}
base.replace
doesn't change the original String
instance, since String
is an immutable class. base.replace
不会更改原始的String
实例,因为String
是一个不可变的类。 Therefore, you must return the output of replace
, which is a new String
. 因此,您必须返回
replace
的输出,这是一个新的String
。
public String withoutString(String base, String remove)
{
return base.replace(remove,"");
}
String#replace()
returns a new string, doesn't change the one it is invoked on, since strings are immutable. String#replace()
返回一个新字符串,不会更改它所调用的字符串,因为字符串是不可变的。 Use this in your code: 在您的代码中使用它:
base = base.replace(remove, "")
Update your code: 更新你的代码:
public String withoutString(String base, String remove) {
//base.replace(remove,"");//<-- base is not updated, instead a new string is builded
return base.replace(remove,"");
}
Apache Commons library has already implemented this method,you don't need to write again. Apache Commons库已经实现了这个方法,你不需要再写一次。
Code : 代码:
return StringUtils.remove(base, remove);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.