在本教程中,我们将看到如何正确填充带空格和零的字符串:
使用空格右填充
public class PadRightExample1 {
public static void main(String[] argv) {
System.out.println("#" + rightPadding("mystring", 10) + "@");
System.out.println("#" + rightPadding("mystring", 15) + "@");
System.out.println("#" + rightPadding("mystring", 20) + "@");
}
public static String rightPadding(String str, int num) {
return String.format("%1$-" + num + "s", str);
}
}
输出:
#mystring @
#mystring @
#mystring @
使用零右填充
public class PadRightExample2 {
public static void main(String[] argv) {
System.out.println("#" + rightPadZeros("mystring", 10) + "@");
System.out.println("#" + rightPadZeros("mystring", 15) + "@");
System.out.println("#" + rightPadZeros("mystring", 20) + "@");
}
public static String rightPadZeros(String str, int num) {
return String.format("%1$-" + num + "s", str).replace(' ', '0');
}
}
输出:
#[email protected]
#[email protected]
#[email protected]