java - 数字转换成以0开头的字符串

简单写就

String.format("%04d", 3)

不过令我意外的是 StringBuilder + replace 效率居然更高

public class Test {
    public static String  format2(int shortval) {
        String formatted = Integer.toString(shortval);
        StringBuilder buf = new StringBuilder("0000");
        buf.replace(4 - formatted.length(), 4, formatted);
        return buf.toString();
    }

    public static void main(String[] args) {
        String s;
        {
            long start = System.nanoTime();
            int cnt = 100_0000;
            while (cnt-- > 0) {
                s = String.format("%04d", 3);
            }
            long end = System.nanoTime();
            System.out.println(end - start);
        }
        {
            long start = System.nanoTime();
            int cnt = 100_0000;
            while (cnt-- > 0) {
                s = format2((short) 3);
            }
            String a ="";
            long end = System.nanoTime();
            System.out.println(end - start);
        }
    }
}

posted on 2019-07-02 18:02  疯狂的妞妞  阅读(2298)  评论(0编辑  收藏  举报

导航