java 如何在java中替换字符串的空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32858955/
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
How to replace null value of a String in java?
提问by Vipul Dhage
I know it's a dumb question but still.
我知道这是一个愚蠢的问题,但仍然如此。
But I want to know is it possible to replace the string which is set to null ?
但我想知道是否可以替换设置为 null 的字符串?
String str=null;
String str2= str.replace('l','o');
System.out.println(str2);
Currently it is giving me NullPointerException
.
目前它正在给我NullPointerException
。
I want to know is it possible to some how replace the value of String which is set to null ?
我想知道是否有可能如何替换设置为 null 的 String 的值?
If Yes, how ?
如果是,如何?
Help appreciated. Thanks
帮助表示赞赏。谢谢
回答by Bohemian
Use String.valueOf()
:
使用String.valueOf()
:
String str2 = String.valueOf(str).replace('l','o');
From the javadoc of String.valueOf(Object obj)
:
来自 的javadoc String.valueOf(Object obj)
:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
如果参数为空,则字符串等于“空”;否则,返回 obj.toString() 的值。
which of course for a String
is itself.
这当然是 aString
本身。
回答by silentprogrammer
回答by S Harish Morampudi
http://www.java-examples.com/java-string-valueof-example
http://www.java-examples.com/java-string-valueof-example
Check it once you may come to know clear idea about Strings
一旦您对字符串有了清晰的认识,请检查它
回答by york yuan
If str is null,str2 will be an empty string
如果 str 为空,则 str2 将为空字符串
String str=null;
String str2= StringUtils.isEmpty(str) ? '' : str.replace('l','o');
System.out.println(str2);