下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
其他回答
StringUtils.leftPad(yourString, 8, '0');
这来自commons-lang。看到javadoc
有人尝试过这个纯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");
不幸的是,这个解决方案只有在字符串中没有空格时才有效。
你可以使用:
String.format("%08d", "Apple");
这似乎是最简单的方法,不需要任何外部库。
这是快速的,适用于任何长度。
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);
}
我喜欢用零填充字符串的解决方案
String.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"