How to format strings in Java

后端 未结 8 1936
执笔经年
执笔经年 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:19

    I've wrote my simple method for it :

    public class SomeCommons {
        /** Message Format like 'Some String {0} / {1}' with arguments */
        public static String msgFormat(String s, Object... args) {
            return new MessageFormat(s).format(args);
        }
    }
    

    so you can use it as:

    SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");
    
    0 讨论(0)
  • 2020-11-22 11:24

    This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this

    /customer/{0}/user/{1}/order
    

    and add as many params as you need:

    public String createURL (String restURL, Object ... params) {       
        return new MessageFormat(restURL).format(params);
    }
    

    You just have to call this method like this:

    createURL("/customer/{0}/user/{1}/order", 123, 321);
    

    The output

    "/customer/123/user/321/order"

    0 讨论(0)
提交回复
热议问题