java字符串數(shù)字補齊位數(shù)詳解
更新時間:2025年03月24日 11:00:22 作者:王小工
這篇文章主要介紹了java字符串數(shù)字補齊位數(shù),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
java字符串數(shù)字補齊位數(shù)
在Java中實現(xiàn)字符串位數(shù)補齊主要有以下幾種常用方法,可根據(jù)不同場景選擇使用:
一、使用String.format()方法
- 1. 左補齊(右側(cè)補空格)
String result = String.format("%10s", "hello"); // 總長度10,左側(cè)補空格?:ml-citation{ref="5" data="citationList"}
- 2. 右對齊(左側(cè)補零)
String str = String.format("%06d", 12345); // 輸出"012345"?:ml-citation{ref="5,7" data="citationList"}
- 3. 自定義補位字符
通過替換空格實現(xiàn)其他字符補齊:
String res = String.format("%5s", "gr").replace(' ', '1'); // 輸出"111gr"?:ml-citation{ref="4" data="citationList"}
二、Apache Commons Lang庫方法
- 使用StringUtils.leftPad()實現(xiàn)左補齊:
String value = StringUtils.leftPad("3123123", 10, "0"); // 輸出"0003123123"?:ml-citation{ref="4" data="citationList"}
三、Java 11+的String.repeat()方法
- 適用于已知需要補足的具體字符數(shù):
String padding = " ".repeat(16 - originalStr.length()); String result = originalStr + padding; // 右補空格至16位?:ml-citation{ref="3" data="citationList"}
四、循環(huán)遍歷實現(xiàn)
- 通過StringBuilder動態(tài)構建補位字符串:
public static String padString(String input, char padChar, int length) { StringBuilder result = new StringBuilder(input); while (result.length() < length) { result.insert(0, padChar); // 左補指定字符?:ml-citation{ref="1" data="citationList"} } return result.toString(); }
五、NumberFormat數(shù)字格式化
- 適用于數(shù)字類型補零:
NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumIntegerDigits(6); // 設置最小整數(shù)位數(shù) String formatted = nf.format(123); // 輸出"000123"?:ml-citation{ref="5" data="citationList"}
選擇建議:
- 原生推薦:優(yōu)先使用String.format(),代碼簡潔且性能較好57
- 第三方庫場景:若項目中已引入Apache Commons Lang,推薦StringUtils.leftPad()4
- 超長補位需求:Java 11+的repeat()方法更高效3
- 歷史兼容性:低版本Java可使用循環(huán)遍歷實現(xiàn)12
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java 11 正式發(fā)布,這 8 個逆天新特性教你寫出更牛的代碼
美國當?shù)貢r間9月25日,Oracle 官方宣布 Java 11 (18.9 LTS) 正式發(fā)布,可在生產(chǎn)環(huán)境中使用!這是自 Java 8 后的首個長期支持版本2018-09-09Nacos下線服務時,下線報錯選舉Leader失敗問題以及解決
這篇文章主要介紹了Nacos下線服務時,下線報錯選舉Leader失敗問題以及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07詳解Maven 搭建spring boot多模塊項目(附源碼)
這篇文章主要介紹了詳解Maven 搭建spring boot多模塊項目(附源碼),具有一定的參考價值,有興趣的可以了解一下2017-09-09