我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
当前回答
如果你需要性能并且知道字符串的最大大小,使用以下方法:
String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;
注意最大字符串大小。如果它大于StringBuffer的大小,你会得到一个java.lang.StringIndexOutOfBoundsException。
其他回答
以下是我的解决方案:
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
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());
}
}
你可以使用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字符)
右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)
String paddedString = org.apache.commons.lang.StringUtils.leftPad("129018", 10, "0")
第二个参数是期望的输出长度
"0"是填充字符