下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。
while(str.length() < desired_length)
str = '0'+str;
其他回答
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);
}
这是快速的,适用于任何长度。
public static String prefixZeros(String value, int len) {
char[] t = new char[len];
int l = value.length();
int k = len-l;
for(int i=0;i<k;i++) { t[i]='0'; }
value.getChars(0, l, t, k);
return new String(t);
}
这并不漂亮,但很有效。如果你有apache commons,我建议你使用它
if (val.length() < 8) {
for (int i = 0; i < val - 8; i++) {
val = "0" + val;
}
}
public static String lpad(String str, int requiredLength, char padChar) {
if (str.length() > requiredLength) {
return str;
} else {
return new String(new char[requiredLength - str.length()]).replace('\0', padChar) + str;
}
}
如果你想用纯Java编写程序,你可以遵循下面的方法,或者有很多String Utils可以帮助你更好地使用更高级的功能。
使用一个简单的静态方法可以实现如下所示。
public static String addLeadingText(int length, String pad, String value) {
String text = value;
for (int x = 0; x < length - value.length(); x++) text = pad + text;
return text;
}
你可以使用上面的方法addLeadingText(长度,填充文本,你的文本)
addLeadingText(8, "0", "Apple");
输出是000Apple