java 将空字符串转换为“”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29529185/
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 15:26:05  来源:igfitidea点击:

Convert null string to ""

javanull

提问by dwjohnston

If I have

如果我有

String a = null;
System.out.println(a);

I'll get

我去拿

null

null

Is there an elegant way to change this an empty string?

有没有一种优雅的方法来改变这个空字符串?

I could do:

我可以做:

if (a == null){
a="";
}

The context is that I'll be producing a string of the form:

上下文是我将生成以下形式的字符串:

String myString = a + "\n" + b + "\n" + c;

String myString = a + "\n" + b + "\n" + c;

But I'm wondering if there's a nicer solution.

但我想知道是否有更好的解决方案。

回答by shauryachats

You could try it like this using the ternary operator.

您可以像这样使用三元运算符尝试它。

System.out.println(a == null ? "" : a);

Alernatively, you can use the Commons Lang3 function defaultString()as suggested by chrylis,

或者,您可以使用 chrylisdefaultString()建议的 Commons Lang3 函数,

System.out.println(StringUtils.defaultString(a));

回答by Bohemian

I would factor out a utility method that captures the intention, which improves readability and allows easy reuse:

我会提取出一种捕获意图的实用方法,它提高了可读性并允许轻松重用:

public static String blankIfNull(String s) {
    return s == null ? "" : s;
}

Then use that when needed:

然后在需要时使用它:

System.out.println(blankIfNull(a));

回答by dwjohnston

Apache commons lang3has a function that will do this.

Apache commons lang3有一个功能可以做到这一点。

import org.apache.commons.lang3.StringUtils;

a = null;
System.out.println(StringUtils.defaultString(a));

回答by Paul Boddington

You could write a varargs method

你可以写一个可变参数方法

public static String concat(String... arr) {
    StringBuilder sb = new StringBuilder();
    for (String s : arr)
        if (s != null)
            sb.append(s);
    return sb.toString();
}

Then you can do

然后你可以做

String myString = concat(a, "\n", b, "\n", c);