Java 中 如何将一个字符重复n遍

方法一:app

String.format("%0" + n + "d", 0).replace("0",s);ide

方法二:性能

new String(new char[n]).replace("\0", s);测试

方法三:(JAVA 8)spa

String.join("", Collections.nCopies(n, s));code

方法四:orm

1 public static String repeatString(String str, int n, String seg) { 2         StringBuffer sb = new StringBuffer(); 3         for (int i = 0; i < n; i++) { 4  sb.append(str).append(seg); 5  } 6         return sb.substring(0, sb.length() - seg.length()); 7     }

 


执行次数1000_000blog

耗时毫秒string

1797io

593

167

142

根据前面的总结和测试,相对而言,3和4的耗时比较少,屡次测试的结果4都比3用时更少一点。

注重性能就选择3或4

 

|--根据以上方法写一个给出n,输出n位数最小值方法

 

1 //输入1,输出1; 输入2,输出10; 输入3,输出100; 输入4,输出1000;
2     public static String convert(int n) { 3         String temp = "0"; 4         String result = "1" + String.join("", Collections.nCopies(n - 1, temp)); 5         return result; 6     }
给一个数字n,输出n位数最小值的方法,好比给一个3,输出3位数的最小值1000
相关文章
相关标签/搜索