Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to replace strings in java

Tags:

java

string

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?

like image 454
hguser Avatar asked Nov 27 '22 14:11

hguser


2 Answers

String template = "http://server/%s/%s/%s/%s/%s.json";
String output = String.format(template, x, y, z, t, a);
like image 127
jlordo Avatar answered Dec 23 '22 06:12

jlordo


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
like image 31
Eng.Fouad Avatar answered Dec 23 '22 06:12

Eng.Fouad