下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
可以更快,然后克里斯勒彻回答时,大部分的字符串恰好有8个字符
int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);
在我的情况下,我的机器快了1/8。
其他回答
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
使用Guava的Strings实用程序类:
Strings.padStart("Apple", 8, '0');
以防你不得不在没有库的帮助下做这件事:
("00000000" + "Apple").substring("Apple".length())
(工作,只要你的字符串不超过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);
}
}
public class PaddingLeft {
public static void main(String[] args) {
String input = "Apple";
String result = "00000000" + input;
int length = result.length();
result = result.substring(length - 8, length);
System.out.println(result);
}
}