zoukankan      html  css  js  c++  java
  • String join()

    今天刷LeetCode的时候看题析,看到一个未曾使用过的方法String.join()

        /**
         * Creates a new String by putting each element together joined by the delimiter. If an element is null, then "null" is used as string to join.
         *
         * @param delimiter
         *          Used as joiner to put elements together
         * @param elements
         *          Elements to be joined
         * @return string of joined elements by delimiter
         * @throws NullPointerException
         *          if one of the arguments is null
         *
         */
        public static String join(CharSequence delimiter, CharSequence... elements) {
            StringJoiner stringJoiner = new StringJoiner(delimiter);
    
            for (CharSequence element : elements) {
                stringJoiner.add(element);
            }
    
            return stringJoiner.toString();
        }

    注释说明这个方法是将后面的可变参数的内容通过前面的delimiter分隔符连接在一起,如果一个内容是null,那么“null”将会作为字符串放到连接中。

    可以看到这里新建了一个StringJoiner对象,里面的具体实现往后再看,这里我们只需要明白这个方法是将elements中的对象通过delimiter连接起来就行,例如:

    List names=new ArrayList<String>();
    
    names.add("1");
    
    names.add("2");
    
    names.add("3");
    
    System.out.println(String.join("-", names));
    
     
    
    String[] arrStr=new String[]{"a","b","c"};
    
    System.out.println(String.join("-", arrStr));
    
    
    输出:
    1-2-3
    a-b-c
  • 相关阅读:
    文本效果
    C# 将数据导出到Execl汇总[转帖]
    using方法的使用
    存储过程的相关记录
    Dictionary 泛型字典集合[转帖]
    JS验证
    浅谈AutoResetEvent的用法 [转帖]
    聊聊xp和scrum在实战中的应用问题
    字体下载
    [转] 前端开发工程师如何在2013年里提升自己
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/12801294.html
Copyright © 2011-2022 走看看