1. 概要

この短いチュートリアルでは、StringをJavaに埋め込む方法を説明します。 主に左側のパッドに焦点を当てます。つまり、目的の長さに達するまで、先頭のスペースまたはゼロを追加します。

右に埋め込まれたStringのアプローチは非常に似ているため、違いのみを指摘します。

2. カスタムメソッドを使用して文字列を埋める

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

First, let’s set some expectations:

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

2.1. StringBuilderを使用する

これは、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();
}

ここで、元のテキストの長さが目的の長さ以上の場合、変更されていないバージョンのテキストが返されることがわかります。 Otherwise, we create a new String, starting with spaces, and adding the original one.

もちろん、 pad with a different character, we could just use it instead of a 0.

同様に、右パッドを使用する場合は、代わりに new StringBuilder(inputString)を実行し、最後にスペースを追加する必要があります。

2.2. substringを使用する

左パディングを行う別の方法は、パディング文字のみを含む目的の長さの文字列を作成してから、substring()メソッドを使用することです。

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

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

2.3. String.formatを使用する

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

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

デフォルトでは、パディング操作はスペースを使用して実行されることに注意してください。 That’s why we need to use the replace() method if we want to pad with zeros or any other character.

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

3. ライブラリを使用して文字列を埋める

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

3.1. Apache Commons Lang

Apache Commons Langは、Javaユーティリティクラスのパッケージを提供します。 One of the most popular ones is StringUtils.

これを使用するには、その依存関係 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.

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.

対応する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.

3.2. Google Guava

Another library that we can use is Google’s 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:

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

このメソッドにはデフォルトのパッド文字がないため、毎回渡す必要があります。

右パッドには、 padEnd()メソッドを使用できます。

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

4. 結論

この簡単な記事では、JavaでStringをパディングする方法を説明しました。 独自の実装または既存のライブラリを使用した例を示しました。

いつものように、完全なソースコードはGitHubにあります。