Efficient way to replace strings in java

I have a string template similar to this:

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

And I have the meanings:

 int x=1,y=2,z=3,t=4,a=5; 

I want to know what is the efficient way to replace {x} with the value of x , and therefore y,z,t,z ?

+4
source share
6 answers

Another way to do this ( 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 
+4
source
 String template = "http://server/%s/%s/%s/%s/%s.json"; String output = String.format(template, x, y, z, t, a); 
+16
source

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

If you can change this 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); 
+3
source

To replace placeholders with exact ones, as you use in the 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 requires replacing x with 0, y with 1, etc.

If you change your format to

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

you can use Velocity , which has a parser specializing in searching for events $ {and}.

The most efficient way would be to write your own parser that will look for the next {{{{{{{{{{{{{{{{}}}} than} than replace the placeholder.

+1
source

This may be the likely 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); 
0
source

Source: https://habr.com/ru/post/1480417/


All Articles