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

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

 
posted @ 2020-06-03 17:36  MrZhaoyx  阅读(1115)  评论(0编辑  收藏  举报