Is there a general string substitution function similar to sl4fj?

If you are looking for a solution where you can replace a bunch of variables in a String with values, you can use StrSubstitutor.

 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";
 StrSubstitutor sub = new StrSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

It follows a generally accepted pattern where one can pass a map with variables to values along with the unresolved String and it returns a resolved String.


String.format

String str = String.format("Action %s occured on object %s.",
   objectA.getAction(), objectB);

Or

String str = String.format("Action %s occured on object %s with outcome %s.",
   new Object[]{objectA.getAction(), objectB, outcome});

You can also use numeric positions, for example to switch the parameters around:

String str = String.format("Action %2$s occured on object %1$s.",
   objectA.getAction(), objectB);

You can use String.format or MessageFormat.format

E.g.,

MessageFormat.format("A sample value {1} with a sample string {0}", 
    new Object[] {"first", 1});

or simply

MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1);

Tags:

Java