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

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

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

总输出长度应为10。


当前回答

基于@Haroldo Macêdo的回答,我在自定义Utils类中创建了一个方法,例如

/**
 * Left padding a string with the given character
 *
 * @param str     The string to be padded
 * @param length  The total fix length of the string
 * @param padChar The pad character
 * @return The padded string
 */
public static String padLeft(String str, int length, String padChar) {
    String pad = "";
    for (int i = 0; i < length; i++) {
        pad += padChar;
    }
    return pad.substring(str.length()) + str;
}

然后打电话给Utils。padLeft(str, 10, "0");

其他回答

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

第二个参数是期望的输出长度

"0"是填充字符

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

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

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

Satish的解决方案在预期的答案中是非常好的。我想通过添加变量n到格式化字符串而不是10个字符来使它更通用。

int maxDigits = 10;
String str = "129018";
String formatString = "%"+n+"s";
String str2 = String.format(formatString, str).replace(' ', '0');
System.out.println(str2);

这在大多数情况下都有效

我用过这个:

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

结果:00123

我希望它对你有用!

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