java join字符串_Java字符串join()

java join字符串

Java String join() function is used to join multiple strings to create a new string with the specified delimiter.

Java String join()函数用于连接多个字符串,以使用指定的分隔符创建新字符串。

Java字符串join() (Java String join())

Java String join() method is added in Java 8 release. There are two variants of join() method, both of them are static methods.

在Java 8版本中添加了Java String join()方法。 join()方法有两种变体,它们都是静态方法 。

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

public static String join(CharSequence delimiter,
            Iterable elements)

The first argument is the delimiter string to use when joining the strings. CharSequence is an interface and some well known implementations are String, StringBuffer and StringBuilder.

第一个参数是连接字符串时要使用的定界符字符串。 CharSequence是一个接口,一些知名的实现是String, StringBuffer和StringBuilder 。

Let’s look at these methods with some example.

让我们通过一些例子来看看这些方法。

String msg1 = String.join(",", "A", "B", new StringBuilder("C"), new StringBuffer("D"));
System.out.println(msg1);

Output: A,B,C,D

输出: A,B,C,D

Notice that I have used StringBuffer and StringBuilder as elements to join since they implement CharSequence interface.

注意,由于它们实现了CharSequence接口,因此我将StringBuffer和StringBuilder用作连接的元素。

Let’s look at an example where we will pass an Iterable whose elements will be joined with the given delimiter.

让我们看一个示例,在此示例中,我们将传递一个Iterable,其元素将与给定的定界符连接在一起。

List words = Arrays.asList(new String[] { "Hello", "World", "2019" });
String msg = String.join(" ", words);
System.out.println(msg);

Output: Hello World 2019

输出: Hello World 2019

We can execute above code snippets using jshell terminal too.

我们也可以使用jshell终端执行以上代码片段。

java join字符串_Java字符串join()_第1张图片

Java String join() Example – jshell

Java字符串join()示例– jshell

GitHub Repository. GitHub存储库中签出更多String示例。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/24730/java-string-join

java join字符串

你可能感兴趣的:(java join字符串_Java字符串join())