下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
下面是字符串,例如:
"Apple"
我想加零来填充8个字符:
"000Apple"
我该怎么做呢?
当前回答
使用Apache Commons StringUtils。leftPad(或者查看代码来创建自己的函数)。
其他回答
使用方法String::repeat的解决方案(Java 11)
String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;
如果需要,将8更改为其他数字或将其参数化
如果你想用纯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
使用Apache Commons StringUtils。leftPad(或者查看代码来创建自己的函数)。
使用Guava的Strings实用程序类:
Strings.padStart("Apple", 8, '0');
在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做的方法)。它和其他的解决方案有点不同,我特别喜欢它。