3
1

More than 3 years have passed since last update.

【Java】string.formatの使い方

Posted at

string.format とは?

引数に指定した書式を元に文字列を整形して返すというメソッドです。

書き方

第一引数は決められた書式に従って書く必要があります。第二引数以降は第一引数で決めた書式に割り当てるための変数を渡します。

public static String format(String format,Object... args)

実装例

指定された書式の文字列と引数を使って、書式付き文字列を返します。
書式は(%〜)と書いて指定します。
整数(10進整数)を整形する場合はd、文字列を整形する場合はsを使います。

        int year = 2021;
        String str = String.format("今年は%d年です。", year);
        System.out.println(str); //今年は2021年です。

        // はじめに0を追加
        System.out.println(String.format("%05d", 1000)); //01000
        System.out.println(String.format("%06d", 1000)); //001000

        // 文字を追加
        System.out.println(String.format("%dと%d", 1000,2000)); //1000と2000

        // 文字列を整形
        System.out.println(String.format("%s/%s/%s", "2021","01","03")); //2021/01/03

3
1
0

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
3
1