Left padding a String with Zeros

This question already has an answer here:

  • How can I pad a String in Java? 26 answers

  • If your string contains numbers only, you can make it an integer and then do padding:

    String.format("%010d", Integer.parseInt(mystring));
    

    If not I would like to know how it can be done.


    org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
    

    the second parameter is the desired output length

    "0" is the padding char


    This will pad left any string to a total width of 10 without worrying about parse errors:

    String unpadded = "12345"; 
    String padded = "##########".substring(unpadded.length()) + unpadded;
    
    //unpadded is "12345"
    //padded   is "#####12345"
    

    If you want to pad right:

    String unpadded = "12345"; 
    String padded = unpadded + "##########".substring(unpadded.length());
    
    //unpadded is "12345"
    //padded   is "12345#####"  
    

    You can replace the "#" characters with whatever character you would like to pad with, repeated the amount of times that you want the total width of the string to be. Eg if you want to add zeros to the left so that the whole string is 15 characters long:

    String unpadded = "12345"; 
    String padded = "000000000000000".substring(unpadded.length()) + unpadded;
    
    //unpadded is "12345"
    //padded   is "000000000012345"  
    

    The benefit of this over khachik's answer is that this does not use Integer.parseInt, which can throw an Exception (for example, if the number you want to pad is too large like 12147483647). The disadvantage is that if what you're padding is already an int, then you'll have to convert it to a String and back, which is undesirable.

    So, if you know for sure that it's an int, khachik's answer works great. If not, then this is a possible strategy.

    链接地址: http://www.djcxy.com/p/46090.html

    上一篇: 参数化类型数组

    下一篇: 用零填充字符串