格式化字串長度不夠補0
阿新 • • 發佈:2019-01-09
最近專案需要格式化字串的指定長度,不夠的前面補零大部分是用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