下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。
while(str.length() < desired_length)
str = '0'+str;
其他回答
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
你可以用这个:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
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);
}
}
我相信这就是他真正想要的:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
输出:
000Apple
以防你不得不在没有库的帮助下做这件事:
("00000000" + "Apple").substring("Apple".length())
(工作,只要你的字符串不超过8个字符。)