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

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

在本教程中，我们将看到如何正确填充带空格和零的字符串：

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

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

**输出：**

```java
#mystring  @
#mystring       @
#mystring            @
```

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

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

**输出：**

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

```