最近项目需要格式化字符串的指定长度,不够的前面补零大部分是用String.format去做的
public static void main(String[] args) {
String str="%04d";
System.out.println(String.format(str, 15));
}
输出:
0015
但是我需要的是格式化字符串,后来我想StringUtils专门处理字符串的会不会也有,后来发现还真有
maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.2.1</version>
</dependency>
上代码
public static void main(String[] args) {
System.out.println(StringUtils.leftPad("ws50", 15, '0'));
System.out.println(StringUtils.rightPad("ws50", 15, 'z'));
}
输出
00000000000ws50
ws50zzzzzzzzzzz