这可以说并不比你的“kludge”更好,但是这里有一个方法可以嵌入到调用中,它将用宽度代替你传递给它的星号。其结果用作实际格式。例如,请考虑以下调用:printf
System.out.printf("%04d %2s %-7d;%n", 65, "a", 6);
我将通过嵌入式函数替换第一个和第三个宽度:
System.out.printf( wf("%0*d %2s %-*d;%n", 4, 7), 65, "a", 6);
代码如下:
public static String wf(String fmt, int... widths) {
return metaWidthFormat('*', fmt, widths);
}
public static String metaWidthFormat(char wmeta, String fmt, int ... widths) {
if (fmt == null) return null;
int wix = 0;
boolean outside = true;
// initial capacity is sufficient for each substituted width to be 2 digs
StringBuilder result = new StringBuilder(fmt.length() + widths.length);
for (char ch : fmt.toCharArray()) {
if (outside) {
result.append(ch);
outside = (ch != '%');
} else {
if (ch == wmeta) {
result.append(widths[wix++]);
} else {
result.append(ch);
}
outside = (ch == wmeta) || (ch == '%') || Character.isAlphabetic(ch);
}
}
return result.toString();
}