首頁  >  文章  >  Java  >  Java中字串常見的拼接方式有哪些

Java中字串常見的拼接方式有哪些

WBOY
WBOY轉載
2023-05-01 12:34:142114瀏覽

方式一: 最常見的方式

        String aa = "今天";
        String bb = "明天";
        System.out.println(aa+bb);

方式二:StringBuilder.append()和StringBuffer.append()

先有StringBuffer後有StringBuilder,兩者就像是孿生雙胞胎,該有的都有,只不過大哥StringBuffer,大部分方法都經過synchronized修飾,所以StringBuffer是線程安全的,但是它效率就相對StringBuilder較低

        String aa = "今天";
        String bb = "明天";
        StringBuilder sber = new StringBuilder();
        StringBuffer sbf = new StringBuffer();
        sber.append(aa).append(bb);
        System.out.println(sber.toString());
        sbf.append(aa).append(bb);
        System.out.println(sbf.toString());

方式三:String類下的cocat()方法

如果拼接的字串是null,concat會拋出NullPointerException。如果拼接的字串是一個空字串(「」),那麼concat的效率就會更高。如果拼接的字串非常多,concat的效率就會下降,因為建立的字串物件越多,開銷就越大。

        String aa = "今天";
        String bb = "明天";
        String concat = aa.concat(bb);
        System.out.println(concat);

方式四:String類別下的join()方法

JDK1.8提供了一個新的字串拼接姿勢:String類別增加了一個靜態方法join,第一個參數為字串連接符

		String aa = "今天";
        String bb = "明天";
        String join = String.join("-", aa, bb);
        System.out.println(join);

方式五:StringJoiner

StringJoiner是JDK1.8,java.util套件中的一個類,用於建構一個由分隔符號重新連接的字元序列

		String aa = "今天";
        String bb = "明天";
        StringJoiner sj = new StringJoiner(":", "[", "]");
        sj.add(aa).add(bb);
        System.out.println(sj.toString());

StringJoiner原始碼

package java.util;

public final class StringJoiner {
    private final String prefix;//前缀
    private final String delimiter;//间隔符
    private final String suffix;//后缀
    private StringBuilder value;//值

    private String emptyValue;//空值

    public StringJoiner(CharSequence delimiter) {
        this(delimiter, "", "");//默认前缀和后缀为"",重载调用
    }

    public StringJoiner(CharSequence delimiter,
                        CharSequence prefix,
                        CharSequence suffix) {
        //间隔符,前缀和后缀判断是否为null,null将抛出异常
        Objects.requireNonNull(prefix, "The prefix must not be null");
        Objects.requireNonNull(delimiter, "The delimiter must not be null");
        Objects.requireNonNull(suffix, "The suffix must not be null"); 
        // 成员变量赋值
        this.prefix = prefix.toString();
        this.delimiter = delimiter.toString();
        this.suffix = suffix.toString();
        this.emptyValue = this.prefix + this.suffix;//空值被设置为只有前后缀
    }
	//设置空值,检查是否为null
    public StringJoiner setEmptyValue(CharSequence emptyValue) {
        this.emptyValue = Objects.requireNonNull(emptyValue,
            "The empty value must not be null").toString();
        return this;
    }

    @Override
    public String toString() {
        if (value == null) {
            return emptyValue;//没有值将返回空值或者后续设置的空值
        } else {
            if (suffix.equals("")) {
                return value.toString();//后缀为""直接返回字符串,不用添加
            } else {
	            //后缀不为"",添加后缀,然后直接返回字符串,修改长度
                int initialLength = value.length();
                String result = value.append(suffix).toString();
                // reset value to pre-append initialLength
                value.setLength(initialLength);
                return result;
            }
        }
    }
    初始化,先添加前缀,有了之后每次先添加间隔符,StringBuilder后续append字符串
    public StringJoiner add(CharSequence newElement) {
        prepareBuilder().append(newElement);
        return this;
    }
	//合并StringJoiner,注意后面StringJoiner 的前缀就不要了,后面的appen进来
    public StringJoiner merge(StringJoiner other) {
        Objects.requireNonNull(other);
        if (other.value != null) {
            final int length = other.value.length();
            // lock the length so that we can seize the data to be appended
            // before initiate copying to avoid interference, especially when
            // merge 'this'
            StringBuilder builder = prepareBuilder();
            builder.append(other.value, other.prefix.length(), length);
        }
        return this;
    }
	//初始化,先添加前缀,有了之后每次先添加间隔符
    private StringBuilder prepareBuilder() {
        if (value != null) {
            value.append(delimiter);
        } else {
            value = new StringBuilder().append(prefix);
        }
        return value;
    }

    public int length() {
        // Remember that we never actually append the suffix unless we return
        // the full (present) value or some sub-string or length of it, so that
        // we can add on more if we need to.
        //不忘添加后缀的长度
        return (value != null ? value.length() + suffix.length() :
                emptyValue.length());
    }
}

方式六:StringUtils.join()

#實戰專案中,我們處理字串的時候,常常會用到這個類別.org. apache.commons.lang3.StringUtils套件下,該方法更善於拼接數組中的字串,並且不用擔心NullPointerException。

		String aa = "今天";
        String bb = "明天";
        String ids[] = {"1","2","3"};
        System.out.println(StringUtils.join(aa,bb,"-","124"));
        String join1 = StringUtils.join(ids,",");
        System.out.println(join1);

以上是Java中字串常見的拼接方式有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除