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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:53:04  来源:igfitidea点击:

How to replace null value of a String in java?

javastring

提问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 Stringis itself.

这当然是 aString本身。

回答by silentprogrammer

I dont know what you are trying to achieve but you can concat empty string to it and it will work

我不知道您要实现什么,但您可以将空字符串连接到它,它会起作用

String str = null;
str += "";
String str2 = str.replace('l', 'o');

System.out.println(str2);

DEMO

演示

回答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);