java 将空字符串替换为空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25903489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing null String to empty String
提问by Nico
I have a small problem, but it's hard for me to solve it.
我有一个小问题,但我很难解决。
I have built a String that is a collection of some object's attributes, constructed and delimited by ||
. But whenever I have some null
attribute, it keeps on printing null
, I want to replace null
with empty string.
我构建了一个字符串,它是一些对象属性的集合,由||
. 但是每当我有一些null
属性时,它就会继续打印null
,我想null
用空字符串替换。
For example, for the input
例如,对于输入
ADS||abc||null||null
I want it to become
我想让它变成
ADS||abc||||
I tried these two, but they didn't work:
我尝试了这两个,但它们不起作用:
string.replace(null,"")
string.replace("null","")
Can someone please help?
有人可以帮忙吗?
回答by lxcky
Since Strings are immutable, you should assign your String variable to the result of the replace
method.
由于字符串是不可变的,您应该将字符串变量分配给replace
方法的结果。
String str = "ADS||abc||null||null to become ADS||abc||||";
str = str.replace("null", "");
System.out.println(str);
Output:
输出:
ADS||abc|||| to become ADS||abc||||
回答by cck3rry
Do you mean below code?
你的意思是下面的代码?
String[] names = new String("ADS||abc||null||null to become ADS||abc||||").split("\|\|");
List<String> list = new ArrayList<>();
for (String name : names) {
list.add(name.replace("null", ""));
}
回答by Ankur Singhal
This works fine.
这工作正常。
public static void main(String[] args) {
String s = "ADS||abc||null||null";
s = s.replace("null", "");
System.out.println(s);
}
Output
输出
ADS||abc||||
回答by SwT
you forgot that string is immutable, add this to your code:
您忘记了字符串是不可变的,请将其添加到您的代码中:
String string = string.replace("null","");