Java.lang.String 类

java.lang.String.join() 方法返回一个由 CharSequence 元素的副本组成的新字符串指定分隔符的副本。

语法

public static String join(CharSequence delimiter, 
                          CharSequence... elements) 

参数

delimiter指定分隔每个元素的分隔符。
elements指定要连接在一起的元素。

返回值

返回由分隔符分隔的元素组成的新字符串。

异常

如果分隔符或元素为 null,则抛出 NullPointerException

示例:

在下面的示例中,join() 方法返回一个新的字符串,其中包含与指定分隔符连接在一起的 CharSequence 元素。

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Programming";
    String str2 = "is";
    String str3 = "fun";

    //使用连接所有字符序列
    //空格作为分隔符
    String MyStr1 = String.join(" ", str1, str2, str3);
    System.out.println("MyStr1 is: " + MyStr1); 

    //使用连接所有字符序列
    //- 作为分隔符
    String MyStr2 = String.join("-", str1, str2, str3);
    System.out.println("MyStr2 is: " + MyStr2);
  }
} 

上述代码的输出将是:

MyStr1 is: Programming is fun
MyStr2 is: Programming-is-fun