I have a string template like this:
http://server/{x}/{y}/{z}/{t}/{a}.json
And I have the values:
int x=1,y=2,z=3,t=4,a=5;
I want to know which is the efficent way to replace the {x} to the value of x, and so does y,z,t,z?
Another way to do it (C# way ;)):
MessageFormat mFormat = new MessageFormat("http://server/{0}/{1}/{2}/{3}/{4}.json");
Object[] params = {x, y, z, t, a};
System.out.println(mFormat.format(params));
OUTPUT:
http://server/1/2/3/4/5.json
To replace the placeholders exact how you use them in example, you can use StrinUtils.replaceEach
org.apache.commons.lang.StringUtils.replaceEach(
"http://server/{x}/{y}/{z}/{t}/{a}.json",
new String[]{"{x}","{y}","{z}","{t}","{a}"},
new String[]{"1","2","3","4","5"});
However, MessageFormat will be more efficient, but requiring to replace x with 0, y with 1 etc.
If you change your format to
"http://server/${x}/${y}/${z}/${t}/${a}.json",
you can consider using Velocity, which has parser specialized on finding ${ and } occurences.
The most efficient way would be to write own parser searching for next { occurence, than }, than replacing the placeholder.
This Could be probable answer.
String url= "http://server/{x}/{y}/{z}/{t}/{a}.json";
int x=1,y=2,z=3,t=4,a=5;
url = url.replaceAll("\\{x\\}", String.valueOf(x));
url = url.replaceAll("\\{y\\}", String.valueOf(y));
url = url.replaceAll("\\{z\\}", String.valueOf(z));
url = url.replaceAll("\\{t\\}", String.valueOf(t));
url = url.replaceAll("\\{a\\}", String.valueOf(a));
System.out.println("url after : "+ url);
http://server/{z}/{x}/{y}.json?http://server/{y}.json?x={x}&y={y}http://server/{1}.json?x={0}&y={1}.