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

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

输入:“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字符)

如果你的字符串只包含数字,你可以让它成为一个整数,然后做填充:

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

如果没有,我想知道如何才能做到。

我更喜欢这样的代码:

public final class StrMgr {

    public static String rightPad(String input, int length, String fill){                   
        String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
        return pad.substring(0, length);              
    }       

    public static String leftPad(String input, int length, String fill){            
        String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
        return pad.substring(pad.length() - length, pad.length());
    }
}

然后:

System.out.println(StrMgr.leftPad("hello", 20, "x")); 
System.out.println(StrMgr.rightPad("hello", 20, "x"));

我用过这个:

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

结果:00123

我希望它对你有用!

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