这是一个非常基本的例子......
它基本上String
用空格填充值以提供对齐...
public class Align {
public static void main(String[] args) {
String values[] = new String[]{
"How is",
"your",
"day"};
int maxLength = 0;
for (String value : values) {
maxLength = Math.max(value.length(), maxLength);
}
System.out.println("Left:");
for (String value : values) {
System.out.println("[" + leftPad(value, maxLength) + "]");
}
System.out.println("\nRight:");
for (String value : values) {
System.out.println("[" + rightPad(value, maxLength) + "]");
}
System.out.println("\nCenter:");
for (String value : values) {
System.out.println("[" + centerPad(value, maxLength) + "]");
}
}
public static String leftPad(String sValue, int iMinLength) {
StringBuilder sb = new StringBuilder(iMinLength);
sb.append(sValue);
while (sb.length() < iMinLength) {
sb.append(" ");
}
return sb.toString();
}
public static String rightPad(String sValue, int iMinLength) {
StringBuilder sb = new StringBuilder(iMinLength);
sb.append(sValue);
while (sb.length() < iMinLength) {
sb.insert(0, " ");
}
return sb.toString();
}
public static String centerPad(String sValue, int iMinLength) {
if (sValue.length() < iMinLength) {
int length = sValue.length();
int left = (iMinLength - sValue.length()) / 2;
int right = iMinLength - sValue.length() - left;
StringBuilder sb = new StringBuilder(sValue);
for (int index = 0; index < left; index++) {
sb.insert(0, " ");
}
for (int index = 0; index < right; index++) {
sb.append(" ");
}
sValue = sb.toString();
}
return sValue;
}
}
这只是输出......
Left:
[How is]
[your ]
[day ]
Right:
[How is]
[ your]
[ day]
Center:
[How is]
[ your ]
[ day ]