Pad a String with Zeros or Spaces in Java – 在Java中用零或空格填充一个字符串

最后修改: 2018年 11月 17日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short tutorial, we’ll see how to pad a String in Java. We’ll focus mainly on a left pad, meaning that we’ll add the leading spaces or zeros to it until it reaches the desired length.

在这个简短的教程中,我们将看到如何在Java中对一个String进行填充。我们将主要关注左移,也就是说,我们将把前面的空格或零加到它上面,直到它达到所需的长度。

The approach for the right padded String is very similar, so we’ll only point out the differences.

右边填充String的方法非常相似,所以我们只指出其中的不同。

2. Pad a String Using Custom Methods

2.使用自定义方法对字符串进行填充

The String class in Java doesn’t provide a convenient method for padding, so let’s create several methods on our own.

Java中的String类并没有提供方便的填充方法,所以让我们自己创建几个方法。

First, let’s set some expectations:

首先,让我们设定一些期望。

assertEquals("    123456", padLeftZeros("123456", 10));
assertEquals("0000123456", padLeftZeros("123456", 10));

2.1. Using StringBuilder

2.1.使用StringBuilder

We can achieve this with StringBuilder and some procedural logic:

我们可以通过StringBuilder和一些程序逻辑来实现这个目标。

public String padLeftZeros(String inputString, int length) {
    if (inputString.length() >= length) {
        return inputString;
    }
    StringBuilder sb = new StringBuilder();
    while (sb.length() < length - inputString.length()) {
        sb.append('0');
    }
    sb.append(inputString);

    return sb.toString();
}

We can see here that if the original text’s length is equal to or bigger than the desired length, we return the unchanged version of it. Otherwise, we create a new String, starting with spaces, and adding the original one.

我们在这里可以看到,如果原始文本的长度等于或大于所需的长度,我们就返回它的未修改版本。否则,我们创建一个新的String,从空格开始,并加上原来的。

Of course, if we wanted to pad with a different character, we could just use it instead of a 0.

当然,如果我们想用一个不同的字符做键盘,我们可以直接用它来代替0

Likewise, if we want to right pad, we just need to do new StringBuilder(inputString) instead and then add the spaces at the end.

同样,如果我们想右移,我们只需要做new StringBuilder(inputString),然后在最后添加空格。

2.2. Using substring

2.2.使用子串

Another way to do the left padding is to create a String with the desired length that contains only pad characters and then use the substring() method:

另一种方法是:创建一个只包含PAD字符的String,然后使用substring()方法来进行左键填充。

StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
    sb.append(' ');
}

return sb.substring(inputString.length()) + inputString;

2.3. Using String.format

2.3.使用String.format

Finally, since Java 5, we can use String.format():

最后,从Java 5开始,我们可以使用String.format()

return String.format("%1$" + length + "s", inputString).replace(' ', '0');

We should note that by default the padding operation will be performed using spaces. That’s why we need to use the replace() method if we want to pad with zeros or any other character.

我们应该注意,默认情况下,填充操作将使用空格进行。这就是为什么我们需要使用replace()方法,如果我们想用零或任何其他字符来填充。

For the right pad, we just have to use a different flag: %1$-.

对于右边的垫子,我们只需要使用一个不同的标志。%1$-

3. Pad a String Using Libraries

3.使用库对一个字符串进行填充

Also, there are external libraries that already offer padding functionalities.

此外,还有一些外部库已经提供了填充功能。

3.1. Apache Commons Lang

3.1.阿帕奇公社朗

Apache Commons Lang provides a package of Java utility classes. One of the most popular ones is StringUtils.

Apache Commons Lang提供了一个Java实用类的包。其中最受欢迎的是StringUtils

To use it, we’ll need to include it into our project by adding its dependency to our pom.xml file:

要使用它,我们需要将其纳入我们的项目,方法是在我们的pom.xml文件中加入其依赖性

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

And then we pass the inputString and the length, just like the methods we created.

然后我们传递inputStringlength,就像我们创建的方法。

We can also pass the padding character:

我们还可以传递填充字符。

assertEquals("    123456", StringUtils.leftPad("123456", 10));
assertEquals("0000123456", StringUtils.leftPad("123456", 10, "0"));

Again, the String will be padded with spaces by default, or we need to explicitly set another pad character.

同样,String默认会用空格填充,或者我们需要明确设置另一个填充字符。

There are also corresponding rightPad() methods.

也有相应的rightPad()方法。

To explore more features of the Apache Commons Lang 3, check out our introductory tutorial. To see other ways of the String manipulation using the StringUtils class, please refer to this article.

要探索Apache Commons Lang 3的更多特性,请查看我们的入门教程要查看使用StringUtils类进行String操作的其他方式,请参考这篇文章

3.2. Google Guava

3.2. Google Guava

Another library that we can use is Google’s Guava.

我们可以使用的另一个库是谷歌的Guava

Of course, we first need to add it to the project by adding its dependency:

当然,我们首先需要通过添加其依赖性将其添加到项目中。

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

And then we use the Strings class:

然后我们使用Strings

assertEquals("    123456", Strings.padStart("123456", 10, ' '));
assertEquals("0000123456", Strings.padStart("123456", 10, '0'));

There is no default pad character in this method, so we need to pass it every time.

该方法中没有默认的PAD字符,所以我们每次都需要传递它。

To right pad, we can use padEnd() method.

要向右移动,我们可以使用padEnd()方法。

The Guava library offers many more features, and we have covered a lot of them. Look here for the Guava-related articles.

Guava库提供了更多的功能,我们已经介绍了很多。请看这里的Guava相关文章

4. Conclusion

4.总结

In this quick article, we illustrated how we can pad a String in Java. We presented examples using our own implementations or existing libraries.

在这篇快速文章中,我们说明了如何在Java中填充一个String。我们介绍了使用我们自己的实现或现有库的例子。

As usual, a complete source code can be found over on GitHub.

像往常一样,完整的源代码可以在GitHub上找到over