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

> 原文： [https://beginnersbook.com/2014/07/java-left-padding-a-string-with-spaces-and-zeros/](https://beginnersbook.com/2014/07/java-left-padding-a-string-with-spaces-and-zeros/)

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

#### 1）使用空格左填充

```java
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);
  }
}
```

**输出：**

```java
#  [email protected]
#       [email protected]
#            [email protected]

```

#### 2）使用零左填充

```java
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');
  }
}
```

**输出：**

```java
#[email protected]
#[email protected]
#[email protected]

```