Ben Chuanlong Du's Blog

It is never too late to learn.

Format String in Java

In [6]:
%%classpath add mvn
org.apache.commons commons-text 1.8
In [9]:
import org.apache.commons.text.StringSubstitutor;
import java.util.Map;
import java.util.HashMap;

Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
System.out.println(resolvedString);
The quick brown fox jumped over the lazy dog.
Out[9]:
null
In [2]:
import java.text.MessageFormat;

Object[] params = new Object[]{"hello", "!"};
String msg = MessageFormat.format("{0} world {1}", params);
System.out.println(msg);
hello world !
Out[2]:
null

String.format

In [4]:
String msg = String.format("Hello! My name is %s, I'm %s.", "Ben", 32);
System.out.println(msg);
Hello! My name is Ben, I'm 32.
Out[4]:
null
In [ ]:

Comments