这是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做?
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);
}
}
如果您必须在没有图书馆帮助的情况下完成此操作:
("00000000" + "Apple").substring("Apple".length())
(只要你的字符串不超过 8 个字符就可以。)
StringUtils.leftPad(yourString, 8, '0');
我相信这就是他真正要求的:
String.format("%0"+ (8 - "Apple".length() )+"d%s",0 ,"Apple");
输出:
000Apple
您可以使用另一个答案中使用的 String.format 方法来生成 0 的字符串,
String.format("%0"+length+"d",0)
这可以通过动态调整格式字符串中前导 0 的数量来解决您的问题:
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
这仍然是一个混乱的解决方案,但优点是您可以使用整数参数指定结果字符串的总长度。
您可以使用这个:
org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")
我也遇到过类似的情况,我也用过这个;它非常简洁,您不必处理长度或其他库。
String str = String.format("%8s","Apple");
str = str.replace(' ','0');
简单、整洁。字符串格式返回
" Apple"
,因此用零替换空格后,它会给出所需的结果。
String input = "Apple";
StringBuffer buf = new StringBuffer(input);
while (buf.length() < 8) {
buf.insert(0, '0');
}
String output = buf.toString();
使用 Apache Commons StringUtils.leftPad(或查看代码来创建自己的函数)。
复制来源:
/**
* Left pad a String with a specified String.
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
}
if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
}
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
您可以使用:
String.format("%08d", "Apple");
这似乎是最简单的方法,不需要任何外部库。
在爪哇中:
String zeroes="00000000";
String apple="apple";
String result=zeroes.substring(apple.length(),zeroes.length())+apple;
在 Scala 中:
"Apple".foldLeft("00000000"){(ac,e)=>ac.tail+e}
您还可以探索 Java 8 中使用流和化简来实现这一点的方法(类似于我使用 Scala 的方式)。它与所有其他解决方案有点不同,我特别喜欢它。
使用 String::repeat 方法的解决方案(Java 11)
String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;
如果需要,将 8 更改为另一个数字或对其进行参数化
我喜欢用零填充字符串
的解决方案String.format("%1$" + length + "s", inputString).replace(' ', '0');
长度=“8”且输入字符串=“Apple”
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);
}
}
您可能需要处理边缘情况。这是一个通用方法。
public class Test {
public static void main(String[] args){
System.out.println(padCharacter("0",8,"hello"));
}
public static String padCharacter(String c, int num, String str){
for(int i=0;i<=num-str.length()+1;i++){str = c+str;}
return 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 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解决方案(没有SpringUtils):
//decimal to hex string 1=> 01, 10=>0A,..
String.format("%1$2s", Integer.toString(1,16) ).replace(" ","0");
//reply to original question, string with leading zeros.
//first generates a 10 char long string with leading spaces, and then spaces are
//replaced by a zero string.
String.format("%1$10s", "mystring" ).replace(" ","0");
不幸的是,只有当字符串中没有空格时,此解决方案才有效。
这速度很快并且适用于任何长度。
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);
}
可以比 Chris Lercher 回答更快,因为 String 中的大多数都恰好有 8 个字符
int length = in.length();
return length == 8 ? in : ("00000000" + in).substring(length);
在我的机器上速度快了 1/8。
这是我用来预填充字符串的简单的无 API“可读脚本”版本。 (简单、可读、可调整)。
while(str.length() < desired_length)
str = '0'+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(length, padding text, your text)
addLeadingText(8, "0", "Apple");
输出将是 000Apple
它并不漂亮,但很有效。如果您可以访问 apache commons,我建议您使用它
if (val.length() < 8) {
for (int i = 0; i < val - 8; i++) {
val = "0" + val;
}
}