我在这里和这里都见过类似的问题。

但我不知道如何左垫字符串与零。

输入:“129018” 输出:“0000129018”

总输出长度应为10。


当前回答

右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)

其他回答

你可以使用apache commons StringUtils

StringUtils.leftPad("129018", 10, "0");

https://commons.apache.org/proper/commons lang/javadocs/api - 2.6 - / - org/apache/commons/lang/stringutils.html # leftPad (% 20 int,以% 20字符)

我用过这个:

DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));

结果:00123

我希望它对你有用!

老问题了,但我也有两个方法。


对于固定(预定义的)长度:

    public static String fill(String text) {
        if (text.length() >= 10)
            return text;
        else
            return "0000000000".substring(text.length()) + text;
    }

对于可变长度:

    public static String fill(String text, int size) {
        StringBuilder builder = new StringBuilder(text);
        while (builder.length() < size) {
            builder.append('0');
        }
        return builder.toString();
    }
String str = "129018";
String str2 = String.format("%10s", str).replace(' ', '0');
System.out.println(str2);

格式化字符串使用

import org.apache.commons.lang.StringUtils;

public class test {

    public static void main(String[] args) {

        String result = StringUtils.leftPad("wrwer", 10, "0");
        System.out.println("The String : " + result);

    }
}

输出:字符串:00000wrwer

其中第一个参数是要格式化的字符串,第二个参数是所需输出长度的长度,第三个参数是字符串要填充的字符。

使用链接下载罐子http://commons.apache.org/proper/commons-lang/download_lang.cgi