首页 > 编程 > Java > 正文

Java 将一个字符重复n遍过程详解

2019-11-26 08:30:22
字体:
来源:转载
供稿:网友

方法一:

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

方法二:

new String(new char[n]).replace("/0", s);

方法三:(JAVA 8)

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

方法四:

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

执行次数1000_000

耗时毫秒

1797

593

167

142

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

注重性能就选择3或4

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

 //输入1,输出1; 输入2,输出10;  输入3,输出100; 输入,输出1000;   public static String convert(int n) {     String temp = "0";     String result = "1" + String.join("", Collections.nCopies(n - 1, temp));     return result;   }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表