int[] nums = { 1, 12, 123, 1234, 12345, 123456 };
for (int num : nums) {
System.out.println("cow" + String.format("%6d", num).replace(' ', '-'));
}
This prints:
cow-----1
cow----12
cow---123
cow--1234
cow-12345
cow123456
The key expression is this:
String.format("%6d", num).replace(' ', '-')
This uses String.format
, digit conversion, width 6 right justified padding with spaces. We then replace
each space (if any) with dash.
Optionally, since the prefix doesn't contain any space in this particular case, you can bring the cow in:
String.format("cow%6d", num).replace(' ', '-')
See also
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…