下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
String input = "Apple";
StringBuffer buf = new StringBuffer(input);
while (buf.length() < 8) {
buf.insert(0, '0');
}
String output = buf.toString();
其他回答
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
我相信这就是他真正想要的:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
输出:
000Apple
使用Guava的Strings实用程序类:
Strings.padStart("Apple", 8, '0');
下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。
while(str.length() < desired_length)
str = '0'+str;