简体   繁体   中英

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 ?

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

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

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
http://server/{x}/{y}/{z}/{t}/{a}.json

如果您可以将其更改为http://server/{0}/{1}/{2}/{3}/{4}.json ,则可以使用MessageFormat

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM