class Scratch {
public static void main(String[] args) {
// 格式化补齐
System.out.println(String.format("%04d", 123));
System.out.println(addZeroForNum("123", 4));
}
/**
* 字符串左补齐
*
* @param str 需补齐字符
* @param strLength 补齐后长度
* @return
*/
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
StringBuilder strBuilder = new StringBuilder(str);
while (strLen < strLength) {
//左补0
strBuilder.insert(0, "0");
//右补0
//strBuilder.insert(strBuilder.length(), "0");
strLen = strBuilder.length();
}
str = strBuilder.toString();
}
return str;
}
/**
* 字符串左补齐 (AI优化版)
*
* @param str 需补齐字符
* @param strLength 补齐后长度
* @return 左补齐后的字符
*/
public static String addZeroForNumAI(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
StringBuilder strBuilder = new StringBuilder(strLength);
// 计算需要补齐的 '0' 的数量
int zerosToAdd = strLength - strLen;
// 先添加足够的 '0'
for (int i = 0; i < zerosToAdd; i++) {
strBuilder.append("0");
}
// 再添加原始字符串
strBuilder.append(str);
str = strBuilder.toString();
}
return str;
}
}
java 字符串左补齐
于 2020-07-09 09:21:55 首次发布