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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM