• 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)
  • 相关阅读:
    Python-读取文件内容
    torch_03_二分类
    torch_02_多项式回归
    pytorch_01_基础_一维线性回归
    LC-KSVD 代码解读
    标签一致项(LC-KSVD)-全文解读
    PCA:主成分分析
    牛客刷题-大佬链接
    调试MATLAB代码
    scroll offset & client总结
  • 原文地址:https://www.cnblogs.com/yangmingxianshen/p/12501335.html
Copyright © 2020-2023  润新知