Let\'s say I have a couple variable and I want to format them so they\'re all aligned, but the variables are different lengths. For example:
String a = \"abc
You can find the longest String
, and then use Apache commons-lang StringUtils to leftPad
both of your String
(s). Something like,
int len = Math.max(a.length(), b.length()) + 2;
a = StringUtils.leftPad(a, len);
b = StringUtils.leftPad(b, len);
Or, if you can't use StringUtils
- you could implement leftPad
. First a method to generate String
of whitespace. Something like,
private static String genString(int len) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Then use it to implement leftPad
- like,
private static String leftPad(String in, int len) {
return new StringBuilder(in) //
.append(genString(len - in.length() - 1)).toString();
}
And, I tested it like,
int len = Math.max(a.length(), b.length()) + 2;
System.out.format("%s %.2f%n", leftPad(a, len), price);
System.out.format("%s %.2f%n", leftPad(b, len), price);
Which outputs (as I think you wanted)
abcdef 4.56
abcdefhijk 4.56