Reputation: 6910
Given I have the following integers:
1, 10, 100
I want to pad them with zeroes to have exactly 3 digits:
001
010
100
and I want to print them prefixed by 10 spaces:
001 //assume 10 spaces from the beginning of the line
010
100
I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.
Below are 2 expressions that I created that accomplish each one of these conditions:
@Test
public void test1() {
String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
int[] nums = {1, 10, 100};
for (int i = 0; i < 3; i++) {
String s = langs[i];
int n = nums[i];
System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
}
}
According to documentation the formatter string has the below form:
%[argument_index$][flags][width][.precision]conversion
but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".
How can this be rewritten to accomplish the above mentioned conditions?
NOTE:
My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:
System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);
EDIT:
My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:
textX 001
textXXX 010
textXX 100
So that the spacing is variable.
Upvotes: 3
Views: 4388
Reputation: 2572
If the two only criterias are the padding of 10 Spaces and zero-padding of the numbers:
final String str = String.format("%10s%03d", " ", 2);
Edit after update from OP:
System.out.printf("%-10s%03d", "abc", 2);
How it Works:
We need two arguments for Our pattern, one for the String of length 10, and one for the integer.
%10s
is a pattern for a String of length 10. In order to left align it, we add the -
: %-10s
. The second argument is the integer of length 3
that we want to left pad With zero: %03d
.
If we dont want to rearrange or reuse an argument for multiple format specifiers, just pass the arguments in the order specified in the pattern.
Upvotes: 7
Reputation: 520948
This answer is based on your latest edit, which revealed this data:
textX 001
textXXX 010
textXX 100
Assuming that the second column always has a width of 3, then your problem distills down to figuring out how many spaces need to be added after the first text column. Here is how you could do this in Java 7:
String text = "textXXX";
int n = 10 - text.length();
String padding = String.format("%0" + n + "d", 0).replace("0", " ");
In Java 8 you could this to get the padding string:
String padding = String.join("", Collections.nCopies(n, " "));
Upvotes: 0