下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
这并不漂亮,但很有效。如果你有apache commons,我建议你使用它
if (val.length() < 8) {
for (int i = 0; i < val - 8; i++) {
val = "0" + val;
}
}
其他回答
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
你可以用这个:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
你可以使用:
String.format("%08d", "Apple");
这似乎是最简单的方法,不需要任何外部库。
String input = "Apple";
StringBuffer buf = new StringBuffer(input);
while (buf.length() < 8) {
buf.insert(0, '0');
}
String output = buf.toString();
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);
}
}