Skip to content

Files

Latest commit

e7fe3be · Oct 13, 2019

History

History
55 lines (41 loc) · 1.35 KB

File metadata and controls

55 lines (41 loc) · 1.35 KB

java - 使用空格和零左填充字符串

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

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

1)使用空格左填充

class LeftPaddingExample1 {
  public static void main(String[] args) {
    System.out.println("#" + padLeftSpaces("mystring", 10) + "@");
    System.out.println("#" + padLeftSpaces("mystring", 15) + "@");
    System.out.println("#" + padLeftSpaces("mystring", 20) + "@");
  }

  public static String padLeftSpaces(String str, int n) {
    return String.format("%1$" + n + "s", str);
  }
}

输出:

#  [email protected]
#       [email protected]
#            [email protected]

2)使用零左填充

class LeftPaddingExample2 {
  public static void main(String[] args) {
    System.out.println("#" + padLeftZeros("mystring", 10) + "@");
    System.out.println("#" + padLeftZeros("mystring", 15) + "@");
    System.out.println("#" + padLeftZeros("mystring", 20) + "@");
 }

  public static String padLeftZeros(String str, int n) {
    return String.format("%1$" + n + "s", str).replace(' ', '0');
  }
}

输出:

#[email protected]
#[email protected]
#[email protected]