下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
如果你想用纯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
其他回答
我也遇到过类似的情况,我用了这个;它是非常简洁的,你不需要处理长度或其他库。
String str = String.format("%8s","Apple");
str = str.replace(' ','0');
简单而利落。字符串格式返回“Apple”,因此在用零替换空格后,它会给出所需的结果。
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;
}
}
使用Guava的Strings实用程序类:
Strings.padStart("Apple", 8, '0');
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
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);
}
}