私はJavaが初めてで、Pythonから来ました。Python では、次のように文字列の書式設定を行います。
>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5
Javaで同じことを複製するにはどうすればよいですか?
私はJavaが初めてで、Pythonから来ました。Python では、次のように文字列の書式設定を行います。
>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5
Javaで同じことを複製するにはどうすればよいですか?
クラスはあなたが求めているもののMessageFormat
ように見えます。
System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
Java には、これと同様に機能 するString.formatメソッドがあります。これを使用する方法の例を次に示します。 これは、これらすべてのオプションが何であるかを説明するドキュメント リファレンスです。%
そして、ここにインラインの例があります:
package com.sandbox;
public class Sandbox {
public static void main(String[] args) {
System.out.println(String.format("It is %d oclock", 5));
}
}
これは「It is 5 oclock」と出力します。
Slf4j には、Python と同様に、引数番号なしで受け入れるMessageFormatter.format()があります。{}
Slf4j は一般的なロギング フレームワークですが、MessageFormatter を使用するためのロギングに Slf4j を使用する必要はありません。
これを行うことができます(String.formatを使用):
int x = 4;
int y = 5;
String res = String.format("%d + %d = %d", x, y, x+y);
System.out.println(res); // prints "4 + 5 = 9"
res = String.format("%d %d", x, y);
System.out.println(res); // prints "4 5"
Log4j 2( log4j-api
) を使用する場合は、 を使用できますParameterizedMessage
。
ParameterizedMessage.format("{} {}", new Object[] {x, y});
また
new ParameterizedMessage("{} {}", x, y).getFormattedMessage(); // there is trimming