How to format strings in Java

后端 未结 8 1929
执笔经年
执笔经年 2020-11-22 10:44

Primitive question, but how do I format strings like this:

\"Step {1} of {2}\"

by substituting variables using Java? In C# it\'s

8条回答
  •  抹茶落季
    2020-11-22 11:13

    Java 15

    There is a new instance method called String::formatted(Object... args) as of Java 15.

    The internal implementation is same to String::format(String format, Object... args).

    Formats using this string as the format string, and the supplied arguments.

    String step1 = "one";
    String step2 = "two";
    
    // results in "Step one of two"
    String string = "Step %s of %s".formatted(step1, step2);     
    

    Advantage: The difference is that the method is not static and the formatting pattern is a string itself from which a new one is created based on the args. This allows chaining to build the format itself first.

    Disadvantage: There is no overloaded method with Locale, therefore uses the default one. If you need to use a custom Locale, you have to stick with String::format(Locale l,String format,Object... args).

提交回复
热议问题