下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
我喜欢用零填充字符串的解决方案
String.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"
其他回答
以防你不得不在没有库的帮助下做这件事:
("00000000" + "Apple").substring("Apple".length())
(工作,只要你的字符串不超过8个字符。)
在Java中:
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.format("%1$" + length + "s", inputString).replace(' ', '0');
with length = "8" and inputString = "Apple"
String input = "Apple";
StringBuffer buf = new StringBuffer(input);
while (buf.length() < 8) {
buf.insert(0, '0');
}
String output = buf.toString();
下面是我用于预填充字符串的简单的无api“可读脚本”版本。(简单,可读,可调)。
while(str.length() < desired_length)
str = '0'+str;