How to format strings in Java

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

提交回复
热议问题