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

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

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

总输出长度应为10。


当前回答

    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));

刚刚在采访中问过这个问题........

我的答案如下,但这个(上面提到的)要好得多——>

管柱。format(“% 05d”,全国矿工工会);

我的回答是:

static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.

    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}

其他回答

检查我的代码,将工作的整数和字符串。

假设第一个数字是129018。我们要给它加上0所以最终字符串的长度是10。为此,您可以使用以下代码

    int number=129018;
    int requiredLengthAfterPadding=10;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

以下是我的解决方案:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

输出:00000101

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

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

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

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


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

    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();
    }

格式化字符串使用

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