原文: https://beginnersbook.com/2014/07/java-left-padding-a-string-with-spaces-and-zeros/

在本教程中,我们将看到如何使用空格和零来填充字符串:

1)使用空格左填充

  1. class LeftPaddingExample1 {
  2. public static void main(String[] args) {
  3. System.out.println("#" + padLeftSpaces("mystring", 10) + "@");
  4. System.out.println("#" + padLeftSpaces("mystring", 15) + "@");
  5. System.out.println("#" + padLeftSpaces("mystring", 20) + "@");
  6. }
  7. public static String padLeftSpaces(String str, int n) {
  8. return String.format("%1$" + n + "s", str);
  9. }
  10. }

输出:

  1. # [email protected]
  2. # [email protected]
  3. # [email protected]

2)使用零左填充

  1. class LeftPaddingExample2 {
  2. public static void main(String[] args) {
  3. System.out.println("#" + padLeftZeros("mystring", 10) + "@");
  4. System.out.println("#" + padLeftZeros("mystring", 15) + "@");
  5. System.out.println("#" + padLeftZeros("mystring", 20) + "@");
  6. }
  7. public static String padLeftZeros(String str, int n) {
  8. return String.format("%1$" + n + "s", str).replace(' ', '0');
  9. }
  10. }

输出:

  1. #[email protected]
  2. #[email protected]
  3. #[email protected]