Python supports the following operation:
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
(Example taken from Python's official documentation )
Is there an equivalent way in Java for performing the exact task?
Thanks
Take a look at http://www.stringtemplate.org/ . Here is an example:
ST hello = new ST("Hello, <name>");
hello.add("name", "World");
System.out.println(hello.render());
prints out:
"Hello World"
I don't know if there is anything equal, but you can do:
String s = "$who likes $what";
s.replace("$who", "tim").replace("$what", "kung pao");
And you will get the same result.
Chunk templates ( http://www.x5dev.com/chunk ) make this kind of thing pretty easy:
Chunk c = new Chunk();
c.append("{$who} likes {$what}");
c.set("who", "tim");
c.set("what", "kung pao");
String output = c.toString();
Or if you have a Map<String,String>
already:
Chunk c = new Chunk();
c.append("{$who} likes {$what}");
Map<String,String> tagValues = getTagValues();
c.setMultiple(tagValues);
c.render(System.out);
Chunk also makes it easy to load templates from a file or a group of files, and supports looping, branching, and presentation filters.
String s = String.format("%s likes %s", "tim", "kung pao");
or
System.out.printf("%s likes %s", "tim", "kung pao");
you can easily do the templating with this too.
String s = "%s likes %s";
String.format(s, "tim", "kung pao");
I think you can use String.format
to achieve this.
http://javarevisited.blogspot.sk/2012/08/how-to-format-string-in-java-printf.html
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.