zoukankan      html  css  js  c++  java
  • JAVA复制字符串并用指定字符串拼接

    因为java中并没有提供复制字符串并用指定字符串拼接的方法。那我们就写一个方法来实现这个功能。

    首先我们先明确想要的效果

    repeatSeparator("Apple","Plus",3); //ApplePlusApplePlusApple
    repeatSeparator("Apple","Plus",1); //Apple

    然后介绍一下用到的方法

    //String.join(String sep,List list)方法,是将list中的元素用指定分隔符sep分隔,并返回一个字符串
    List idList = new ArrayList<String>();
    idList.add("1");
    idList.add("2");
    idList.add("3");
    System.out.println(String.join("-", idList));    //1-2-3
    
    //Collections.nCopies(int count,String str)方法,是创建一个count大小的列表,并向列表中添加count个str
    System.out.println(Collections.nCopies(3,"Apple"));    //["Apple","Apple","Apple"]

    这个方法编写起来也十分简单

    String repeatSeparator(String word, String sep, int count) {
            return String.join(sep, Collections.nCopies(count, word));
    }

    上面这种方法可以在java8中实现。当然,若你使用java11,也可以使用java11新特性中新增的方法来实现这个功能

    //java11
    String repeatSeparator(String word, String sep, int count) {
        return (word + sep).repeat(count-1) + word;
    }

    repeat方法具有复制字符串功能

    //repeat复制字符串
    "JAVA11".repeat(3);    //JAVA11JAVA11JAVA11

    这就是复制字符串并用指定字符串拼接的方法,希望能帮助到大家,如果有更好的方法可以交流一下。

     
  • 相关阅读:
    POJ1222_EXTENDED LIGHTS OUT
    SGU196_Matrix Multiplication
    ZOJ3772_Calculate the Function
    Triangle POJ
    POJ 2187 Beauty Contest(凸包,旋转卡壳)
    [Neerc2016]Mole Tunnels (模拟费用流)
    [2019ccpc网络赛】K-th occurrence(后缀数组+主席树)
    【HDU2019多校】E
    Gym
    P3160 [CQOI2012]局部极小值(dfs+状压dp)
  • 原文地址:https://www.cnblogs.com/MrZhaoyx/p/13038981.html
Copyright © 2011-2022 走看看