Correct format string for String.format or similar

后端 未结 4 862
梦如初夏
梦如初夏 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 01:59

    If you want to use empty placeholders (without positions), you could write a small utility around Message.format(), like this

        String format(String s, Object... var2) {
            int i = 0;
            while(s.contains("{}")) {
                s = s.replaceFirst(Pattern.quote("{}"), "{"+ i++ +"}");
            }
            return MessageFormat.format(s, var2);
        }
    

    And then, can use it like,

    format("Some {} {} {}", var1, var2, var3);
    

提交回复
热议问题