在 Java 中连接空字符串的正确方法是什么?

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

What is the right approach to concatenating a null String in Java?

javastringconcat

提问by syntagma

I know that the following:

我知道以下几点:

String s = null;
System.out.println("s: " + s);

will output: s: null.

将输出:s: null

How do I make it output just s: ??

我如何让它只输出s: ?

In my case this is important as I have to concatenate Stringfrom 4values, s1, s2, s3, s4, where each of these values may or may nothave nullvalue.

在我而言,这是重要的,因为我有来连接String4个s1, s2, s3, s4其中每个值可能会或可能不会具有null价值

I am asking this question as I don't want to check for every combinations of s1 to s4(that is, check if these variables are null)or replace "null"with emptyStringat the end, as I think there may be some better ways to do it.

我问这个问题,因为我不想要检查的S1到S4每一个组合(即检查是否这些变量null或更换"null"emptyString在最后,我想可能有一些更好的方式来做到这一点。

采纳答案by Stephen C

The most concise solution this is:

最简洁的解决方案是:

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

or maybe create or use a static helper method to do the same; e.g.

或者创建或使用静态辅助方法来做同样的事情;例如

System.out.println("s: " + denull(s));


However, this question has the "smell" of an application that is overusing / misusing null. It is better to only use / return a nullif it has a specific meaning that is distinct (and needs to be distinct) from the meanings of non-null values.

但是,这个问题具有过度使用/误用的应用程序的“气味” nullnull如果它具有与非空值的含义不同(并且需要不同)的特定含义,则最好仅使用 / 返回 a 。

For example:

例如:

  • If these nulls are coming from String attributes that have been default initialized to null, consider explicitly initializing them to ""instead.
  • Don't use nullto denote empty arrays or collections.
  • Don't return nullwhen it would be better to throw an exception.
  • Consider using the Null Object Pattern.
  • 如果这些空值来自默认初始化为 的字符串属性null,请考虑将它们显式初始化为""
  • 不要null用于表示空数组或集合。
  • null当最好抛出异常时不要返回。
  • 考虑使用空对象模式

Now obviously there are counter-examples to all of these, and sometimes you have to deal with a pre-existing API that gives you nulls ... for whatever reason. However, in my experience it is better to steer clear of using null... most of the time.

现在显然所有这些都有反例,有时你必须处理一个预先存在的 API,它会给你空值......无论出于何种原因。但是,根据我的经验,在null大多数情况下最好避免使用...。

So, in your case, the better approach may be:

因此,就您而言,更好的方法可能是:

String s = "";  /* instead of null */
System.out.println("s: " + s);

回答by user3717646

Try this

尝试这个

String s = s == null ? "" : s;
System.out.println("s: " + s);

A string variable (here, s) is called nullwhen there is no any objects assigned into the variable. So initialize the variale with a empty string which is ""; Then you can concatenate strings.

当没有任何对象分配给变量时,s将调用字符串变量(此处为)null。所以用一个空字符串初始化变量,即""; 然后你可以连接字符串。

If your s variable may be null or not null, Use conditional operator before using it further. Then the variable sis not null further.

如果您的 s 变量可能为空或不为空,请在进一步使用之前使用条件运算符。然后变量s不再为空。

This is a sample Code:

这是一个示例代码:

    String s1 = "Some Not NULL Text 1 ";
    String s2 = null;
    String s3 = "Some Not NULL Text 2 ";

    s1 = s1 == null ? "" : s1;
    s2 = s2 == null ? "" : s2;
    s3 = s3 == null ? "" : s3;

    System.out.println("s: " + s1 + s2 + s3);

Sample Output:

示例输出:

s: Some Not NULL Text 1 Some Not NULL Text 2

s: Some Not NULL Text 1 Some Not NULL Text 2

回答by Rohit Jain

You can use Apache Commons StringUtils.defaultString(String)method, or you can even write your own method that would be just one liner, if you're not using any 3rd party library.

如果您不使用任何 3rd 方库,您可以使用Apache CommonsStringUtils.defaultString(String)方法,或者您甚至可以编写自己的方法,该方法只是一个衬垫。

private static String nullToEmptyString(String str) {
    return str == null ? "" : str;
}

and then use it in your sysout as so:

然后在您的系统输出中使用它:

System.out.println("s: " + nullToEmptyString(s));

回答by David Ehrmann

String s = null;
System.out.println("s: " + (s != null ? s : ""));

But what you're reallyasking for is a null coalescing operator.

但是您真正需要的是一个空合并运算符

回答by CoderCroc

You can declare your own method for concatenation:

您可以声明自己的方法concatenation

public static String concat(String... s) 
{//Use varArgs to pass any number of arguments
    if (s!=null) {
       StringBuilder sb = new StringBuilder();
       for(int i=0; i<s.length; i++) {
          sb.append(s[i] == null ? "" : s[i]);
       }
       return sb.toString();
    }
    else {
        return "";
    }
}

回答by skiwi

You may use the following with Java 8:

您可以在 Java 8 中使用以下内容:

String s1 = "a";
String s2 = null;
String s3 = "c";
String s4 = "d";
String concat = Stream.of(s1, s2, s3, s4)
        .filter(s -> s != null)
        .collect(Collectors.joining());

gives

abc

A few things to note:

需要注意的几点:

  • You can turn data structures (lists, etc.) directly into a Stream<String>.
  • You can also give a delimiter when joining the strings together.
  • 您可以将数据结构(列表等)直接转换为Stream<String>.
  • 您还可以在将字符串连接在一起时提供分隔符。

回答by Fabio Marcolini

Two method comes to mind, the first one is not using concatenation but is safest:

想到了两种方法,第一种不使用串联但最安全:

public static void substituteNullAndPrint(String format, String nullString, Object... params){
    String[] stringParams = new String[params.length()];
    for(int i=0; i<params.length(); i++){
        if(params[i] == null){
            stringParams[i] = nullString;
        }else{
            stringParams[i] = params[i].toSTring();
        }
    }

    String formattedString = String.format(format, stringParams);
    System.out.println(formattedString);
}

USAGE:
substituteNullAndPrint("s: %s,%s", "", s1, s2);

The second use concatenation but require that your actual string is never contains "null", so it may be utilizable only for very simple cases(Anyway even if you string are never "null" I would never use it):

第二次使用连接但要求您的实际字符串永远不会包含“null”,因此它可能仅适用于非常简单的情况(无论如何,即使您的字符串永远不会是“null”,我也永远不会使用它):

public static void substituteNullAndPrint(String str){
    str.replace("null", "");
    System.out.println(str);
}

USAGE:
substituteNullAndPrint("s: " + s1);

NOTES:

笔记:

-Both make use of external utility method since I'm against inlining lot of conditionals.

- 两者都使用外部实用程序方法,因为我反对内联很多条件。

-This is not tested and I might being confusing c# syntax with Java

- 这没有经过测试,我可能会将 c# 语法与 Java 混淆

回答by Stuart Marks

Another approach is to use java.util.Objects.toString()which was added in Java 7:

另一种方法是使用java.util.Objects.toString()Java 7 中添加的:

String s = null;
System.out.println("s: " + Objects.toString(s, ""));

This works for any object, not just strings, and of course you can supply another default value instead of just the empty string.

这适用于任何对象,而不仅仅是字符串,当然您可以提供另一个默认值而不仅仅是空字符串。