Java核心类——StringJoiner

我们在需要进行字符串拼接的时候,可以使用StringBuilder进行拼接:

public class catchExample2 {
    public static void main(String[] args) {
        String[] names = {"bao","ke","mao"};
        StringBuilder s = new StringBuilder();
        s.append("Hello ");
        for (String name:names) {
            s.append(name).append(", ");
            s.delete(s.length() -2, s.length());
            s.append("!");
        }
        System.out.println(s);
    }
}
//执行结果:
Hello bao! ke! mao!

Java还提供了另一个类,StringJoiner用于字符串拼接:

public class catchExample2 {
    public static void main(String[] args) {
        String[] names = {"bao","ke","mao"};
        StringJoiner s = new StringJoiner(", ", "Hello","!");  //分隔符,开始符,结束符
        for (String name : names) {
            s.add(name);
        }
        System.out.println(s);
    }
}

我们首先可以看下StringJoiner的构造函数:

public StringJoiner(
                    CharSequence delimiter,
                    CharSequence prefix,
                    CharSequence suffix) {
    //参数检测
    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");
    // make defensive copies of arguments
    this.prefix = prefix.toString();
    this.delimiter = delimiter.toString();
    this.suffix = suffix.toString();
    this.emptyValue = this.prefix + this.suffix;
}

关于每个参数的解释:
  delimiter:每个字符之间使用的字符序列
  prefix:开头要使用的字符序列
  suffix:最后使用的字符序列

其实StringJoiner内部也是调用StringBuilder来进行构建的:

public StringJoiner add(CharSequence newElement) {
    prepareBuilder().append(newElement);
    return this;
}

private StringBuilder prepareBuilder() {
    if (value != null) {
        value.append(delimiter);
    } else {
        value = new StringBuilder().append(prefix);
    }
    return value;
}

String还提供了一个静态方法join(),这个方法在内部使用了StringJoiner来拼接字符串,
在不需要指定开头和结尾的时候,String.join()更方便。

String[] names = {"mao", “xian”,"ke"}
var s = String.join(", ", names)

 

posted @ 2020-03-16 00:20  明王不动心  阅读(278)  评论(0编辑  收藏  举报