📜  何时在 StringBuilder 上使用 StringJoiner?

📅  最后修改于: 2022-05-13 01:55:32.380000             🧑  作者: Mango

何时在 StringBuilder 上使用 StringJoiner?

先决条件:StringJoiner
当您需要在 Stream 中加入字符串时,StringJoiner 非常有用。
任务:假设我们想要字符串“[George:Sally:Fred]”,其中我们给出了一个包含“George”、“Sally”和“Fred”的字符串数组。
StringJoiner 提供add(String str)方法来根据构造函数中提供的分隔符、前缀和后缀连接字符串,但是如果我们使用 StringBuilder 执行我们的任务,那么首先我们必须附加前缀,然后遍历字符串数组并附加所需的每个元素后的分隔符,最后附加前缀。下面是演示这两种方式的Java程序。

Java
// Java program to demonstrate use of
// StringJoiner class over StringBuilder class
 
import java.util.StringJoiner;
 
public class Test
{
    public static void main(String[] args)
    {
        // given string array
        String str[] = {"George","Sally","Fred"};
             
        // By using StringJoiner class
             
        // initializing StringJoiner instance with
        // required delimiter, prefix and suffix
        StringJoiner sj = new StringJoiner(":", "[", "]");
             
        // concatenating strings
        sj.add("George").add("Sally").add("Fred");
             
        // converting StringJoiner to String
        String desiredString = sj.toString();
             
        System.out.println(desiredString);
             
        // By using StringBuilder class
             
        // declaring empty stringbuilder
        StringBuilder sb = new StringBuilder();
             
        // appending prefix
        sb.append("[");
             
        // checking for empty string array
        if(str.length>0)
        {
            // appending first element
            sb.append(str[0]);
                 
            // iterating through string array
            // and appending required delimiter
            for (int i = 1; i < str.length; i++)
            {
                sb.append(":").append(str[i]);
            }
        }
             
        // finally appending suffix
        sb.append("]");
             
        // converting StringBuilder to String
        String desiredString1 = sb.toString();
             
        System.out.println(desiredString1);
    }
}


输出:

[George:Sally:Fred]
[George:Sally:Fred]