Correct format string for String.format or similar

后端 未结 4 908
梦如初夏
梦如初夏 2021-02-05 01:21

I\'m sure I\'ve seen String.format used like this before:

String.format(\"Some {1}, {2}, {3}\", var1, var2, var3);

Does this ring

4条回答
  •  甜味超标
    2021-02-05 02:08

    Yes, that's the typical format string of C#. In Java, you can use the latter, that is, String.format("%s %d %d", ...).

    An alternative is to use MessageFormat.format("Some {0}, {1}, {2}", var1, var2, var3), which uses the .NET curly braces notation, as mentioned by @Tobias, though it requires you to import java.text.MessageFormat. They are also more appropriate for when you are dealing with localized resources, where you typically have external .properties files with messages in the format Error {0} ocurred due to {1}.

提交回复
热议问题