hguser
hguser

Reputation: 36028

Efficient way to replace strings in java

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?

Upvotes: 4

Views: 930

Answers (6)

Chakit Patel
Chakit Patel

Reputation: 11

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);

Upvotes: 0

Cjxcz Odjcayrwl
Cjxcz Odjcayrwl

Reputation: 22847

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.

Upvotes: 1

Rahul
Rahul

Reputation: 16335

Use MessageFormat.java

MessageFormat messageFormat = new MessageFormat("http://server/{0}/{1}/{2}/{3}/{4}.json");
Object[] args = {x,y,z,t,a};
String result = messageFormat.format(args);

Upvotes: 4

Eng.Fouad
Eng.Fouad

Reputation: 117589

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

Upvotes: 4

user207421
user207421

Reputation: 310884

http://server/{x}/{y}/{z}/{t}/{a}.json

If you can change that to http://server/{0}/{1}/{2}/{3}/{4}.json you can use MessageFormat:

String s = MessageFormat.format("http://server/{0}/{1}/{2}/{3}/{4}.json", x, y, z, t, a);

Upvotes: 3

jlordo
jlordo

Reputation: 37813

String template = "http://server/%s/%s/%s/%s/%s.json";
String output = String.format(template, x, y, z, t, a);

Upvotes: 16

Related Questions