下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
我也遇到过类似的情况,我用了这个;它是非常简洁的,你不需要处理长度或其他库。
String str = String.format("%8s","Apple");
str = str.replace(' ','0');
简单而利落。字符串格式返回“Apple”,因此在用零替换空格后,它会给出所需的结果。
其他回答
我也遇到过类似的情况,我用了这个;它是非常简洁的,你不需要处理长度或其他库。
String str = String.format("%8s","Apple");
str = str.replace(' ','0');
简单而利落。字符串格式返回“Apple”,因此在用零替换空格后,它会给出所需的结果。
使用Apache Commons StringUtils。leftPad(或者查看代码来创建自己的函数)。
我喜欢用零填充字符串的解决方案
String.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"
以防你不得不在没有库的帮助下做这件事:
("00000000" + "Apple").substring("Apple".length())
(工作,只要你的字符串不超过8个字符。)
你可能得处理edgecase。这是一个泛型方法。
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;
}
}