没有针对此类特定用例的公共 API。这是解决它的一种方法:
int num = 65;
int i1 = num > 25 ? 25 : num;
int i2 = num < 25 ? 0 : num > 60 ? 35 : num - 25;
int i3 = num < 60 ? 0 : num - 60;
System.out.format("%02d|%02d|%02d", i1, i2, i3);
印刷
25|35|05
或者,概括一下:
public static String format(String format, int num) {
String[] split = format.split("\\|");
int numLeft = num;
StringBuilder result = new StringBuilder();
for (int i = 0; i < split.length; i++) {
int boundary = Integer.parseInt(split[i]);
int number = Math.min(numLeft, boundary);
if (result.length() > 0) {
result.append('|');
}
result.append(leftPad(number, split[i].length()));
numLeft = Math.max(0, numLeft - boundary);
}
return result.toString();
}
private static String leftPad(int number, int length) {
StringBuilder sb = new StringBuilder();
sb.append(number);
while (sb.length() < length) {
sb.insert(0, '0');
}
return sb.toString();
}
public static void main(String[] args) {
String result = format("25|35|40", 65);
System.out.println(result);
}