8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】文字列のパディング

Posted at

文字列が指定の桁数になるようにパディングしたい時は、**「String.format」**メソッドを使用します。

##String.format

###文字列の空白埋め

padding.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String result5keta = blankPadding5keta();
        String result10keta = blankPadding10keta();
        System.out.println(result5keta);
        System.out.println(result10keta);
    }

    // 5桁で空白埋め
    private static String blankPadding5keta(){
        String str = "123";
        String paddingStr = str.format("%5s", str);

        return paddingStr;
    }

    // 10桁で空白埋め
    private static String blankPadding10keta(){
        String str = "12345";
        String paddingStr = str.format("%10s", str);

        return paddingStr;
    }
}
結果
  12345
     12345

###文字列の0埋め

padding.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String result5keta = zeroPadding5keta();
        String result10keta = zeroPadding10keta();
        System.out.println(result5keta);
        System.out.println(result10keta);
    }

    // 5桁で0埋め
    private static String zeroPadding5keta(){
        String str = "123";
        String paddingStr = str.format("%5s", str).replace(" ", "0");
        
        return paddingStr;
    }

    // 10桁で0埋め
    private static String zeroPadding10keta(){
        String str = "12345";
        String paddingStr = str.format("%10s", str).replace(" ", "0");
        
        return paddingStr;
    }
}
結果
00123
0000012345
8
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?