码迷,mamicode.com
首页 > 其他好文 > 详细

数字格式化成以0开头的定长字符串

时间:2019-07-02 19:17:54      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:格式   length   nan   end   开头   ret   stringbu   rgs   while   

简单写就
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);
        }
    }
}

 

数字格式化成以0开头的定长字符串

标签:格式   length   nan   end   开头   ret   stringbu   rgs   while   

原文地址:https://www.cnblogs.com/chenss15060100790/p/11122271.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!