Java里如何将一个字符串重复n次 (新)
【说明】
以下代码提供了两种方案,一种是基于java的Collections.nCopies实现的,普适性好,效率稍低;一种是基于字符串数组拼接实现的,效率稍高。
各位请自行选择。
【代码】
import java.util.Collections; public class Test { public static void main(String[] args) { // 示例用法 System.out.println("(repeatString1)星号重复4次:"+repeatString1("*",4)); System.out.println("(repeatString2)星号重复4次:"+repeatString2("*",4)); System.out.println("(repeatString1)abcde_重复5次:"+repeatString1("abcde_",5)); System.out.println("(repeatString2)abcde_重复5次:"+repeatString2("abcde_",5)); // 效率比较 long startMs=System.currentTimeMillis(); for(int i=0;i<100000;i++) { repeatString1("abcde",4); } long endMs=System.currentTimeMillis(); System.out.println("repeatString1运行十万次耗时:"+ms2DHMS(startMs,endMs)); startMs=System.currentTimeMillis(); for(int i=0;i<100000;i++) { repeatString2("abcde",4); } endMs=System.currentTimeMillis(); System.out.println("repeatString2运行十万次耗时:"+ms2DHMS(startMs,endMs)); } /** * 重复种子N次,耗时稍长 * @param seed * @param n * @return */ public static String repeatString1(String seed, int n) { return String.join("", Collections.nCopies(n, seed)); } /** * 重复种子N次,耗时稍短 * @param seed * @param n * @return */ public static String repeatString2(String seed, int n){ final int seedLen=seed.length(); final char[] srcArr=seed.toCharArray(); char[] dstArr=new char[n*seedLen]; for(int i=0;i<n;i++){ for(int j=0;j<seedLen;j++){ dstArr[i*seedLen+j]=srcArr[j]; } } return String.valueOf(dstArr); } private static String ms2DHMS(long startMs, long endMs) { String retval = null; long secondCount = (endMs - startMs) / 1000; String ms = (endMs - startMs) % 1000 + "ms"; long days = secondCount / (60 * 60 * 24); long hours = (secondCount % (60 * 60 * 24)) / (60 * 60); long minutes = (secondCount % (60 * 60)) / 60; long seconds = secondCount % 60; if (days > 0) { retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s"; } else if (hours > 0) { retval = hours + "h" + minutes + "m" + seconds + "s"; } else if (minutes > 0) { retval = minutes + "m" + seconds + "s"; } else if(seconds > 0) { retval = seconds + "s"; }else { return ms; } return retval + ms; } }
【运行效果】
(repeatString1)星号重复4次:**** (repeatString2)星号重复4次:**** (repeatString1)abcde_重复5次:abcde_abcde_abcde_abcde_abcde_ (repeatString2)abcde_重复5次:abcde_abcde_abcde_abcde_abcde_ repeatString1运行十万次耗时:78ms repeatString2运行十万次耗时:15ms
END