下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
你可以使用:
String.format("%08d", "Apple");
这似乎是最简单的方法,不需要任何外部库。
其他回答
public static void main(String[] args)
{
String stringForTest = "Apple";
int requiredLengthAfterPadding = 8;
int inputStringLengh = stringForTest.length();
int diff = requiredLengthAfterPadding - inputStringLengh;
if (inputStringLengh < requiredLengthAfterPadding)
{
stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
}
System.out.println(stringForTest);
}
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
可以更快,然后克里斯勒彻回答时,大部分的字符串恰好有8个字符
int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);
在我的情况下,我的机器快了1/8。
public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above.
// The length of the formatted string will be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
有人尝试过这个纯Java解决方案吗(没有SpringUtils):
//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros.
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string.
String.format("%1$10s", "mystring" ).replace(" ","0");
不幸的是,这个解决方案只有在字符串中没有空格时才有效。