Java中连接2个字符串的方法

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

Method to concatenate 2 Strings in Java

javastringrefactoringconcatenation

提问by Ryan

I have a method in Java that concatenates 2 Strings. It currently works correctly, but I think it can be written better.

我在 Java 中有一个连接 2 个字符串的方法。它目前工作正常,但我认为它可以写得更好。

public static String concat(String str1, String str2) {
  String rVal = null;
  if (str1 != null || str2 != null) {
    rVal = "";
    if (str1 != null) {
      rVal += str1;
    }
    if (str2 != null) {
      rVal += str2;
    }      
  }    
  return rVal;
}

Here are some of the requirements:

以下是一些要求:

  1. If both str1 and str2 are null, the method returns null
  2. If either str1 or str2 is null, it will just return the not null String
  3. If str1 and str2 are not null, it will concatenate them
  4. It never adds "null" to the result
  1. 如果 str1 和 str2 都为 null,则该方法返回 null
  2. 如果 str1 或 str2 为空,它将只返回非空字符串
  3. 如果 str1 和 str2 不为空,则将它们连接起来
  4. 它永远不会在结果中添加“null”

Can anyone do this with less code?

任何人都可以用更少的代码来做到这一点吗?

采纳答案by Jon Skeet

Sure:

当然:

public static String concat(String str1, String str2) {
  return str1 == null ? str2
      : str2 == null ? str1
      : str1 + str2;
}

Note that this takes care of the "both null" case in the first condition: if str1is null, then you either want to return null (if str2is null) or str2(if str2is not null) - both of which are handled by just returning str2.

请注意,这会处理第一个条件中的“均为空”情况:如果str1为空,那么您要么想要返回空值(如果str2为空值)或str2(如果str2不是空值)——这两者都通过返回来处理str2

回答by Michael Borgwardt

Using only plain ifclauses:

仅使用普通if子句:

public static String concat(String str1, String str2) {
    if(str1==null) return str2;
    if(str2==null) return str1;
    return str1 + str2;
}

Or, if you have a deep and passionate love for parentheses:

或者,如果您对括号有着深厚而热情的爱:

public static String concat(String str1, String str2) {
    if(str1==null)
    { 
        return str2;
    }
    if(str2==null) 
    {
        return str1;
    }
    return str1 + str2;
}

回答by nishu

import org.apache.commons.lang.StringUtils;

StringUtils.join([str1, str2]);

Joins the elements of the provided array into a single String containing the provided list of elements.

将提供的数组的元素连接到包含提供的元素列表的单个字符串中。

No separator is added to the joined String. Null objects or empty strings within the array are represented by empty strings.

没有分隔符添加到连接的字符串。数组中的空对象或空字符串由空字符串表示。

 StringUtils.join(null)            = null
 StringUtils.join([])              = ""
 StringUtils.join([null])          = ""
 StringUtils.join(["a", "b", "c"]) = "abc"
 StringUtils.join([null, "", "a"]) = "a"

回答by Striker

Everyone seems to have missed condition 1 where if both strings are null it returns null. The simplest version to read (IMO) then becomes:

每个人似乎都错过了条件 1,如果两个字符串都为 null,则返回 null。最简单的阅读版本(IMO)然后变成:

public static String concat(String str1, String str2) {  
    if(str1==null && str2==null) return null;  
    if(str1==null) return str2;  
    if(str2==null) return str1;  
    return str1 + str2;  
}

回答by Carl Manaster

public class ConcatTest extends TestCase {

    // 1. If both str1 and str2 are null, the method returns null
    public void testBothNull() throws Exception {
        assertNull(concat(null, null));
    }

    // 2. If either str1 or str2 is null, it will just return the not null
    // String
    public void testOneNull() throws Exception {
        assertEquals("a", concat(null, "a"));
        assertEquals("b", concat("b", null));
    }

    // 3. If str1 and str2 are not null, it will concatenate them
    public void testNonNull() throws Exception {
        assertEquals("ab", concat("a", "b"));
    }

    // 4. It never adds "null" to the result (not really testable)

    public static String concat(String a, String b) {
        if (a == null && b == null)
            return null;
        return denulled(a) + denulled(b);
    }

    private static String denulled(String s) {
        return s == null ? "" : s;
    }

}