See String.format method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
Answer from Grzegorz Żur on Stack OverflowSee String.format method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
StrSubstitutor from Apache Commons Lang may be used for string formatting with named placeholders:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html :
Substitutes variables within a string by values.
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.
Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
Example:
String template = "Hi ${name}! Your number is ${number}";
Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");
String formattedString = StrSubstitutor.replace(template, data);
How to use integers in a String with placeholders
String template with named placeholders
There will be no String Template in JDK 23.
JEP: String Templates (Final) for Java 22
Hi, Im new to learning Java and have been trying to format a String so i can just call it with Sys.out rather than having to type the entire String each time, however it doesn't seem to update. My code is below
int currentDay = 1;
int currentMonth = 2;
String currentDate = String.format("The current date is: %d of %d", currentDay, currentMonth);
System.out.println(currentDate);
Scanner in = new Scanner(System.in);
System.out.println("New day: ");
currentDay = in.nextInt();
System.out.println("New Month: ");
currentMonth = in.nextInt();
System.out.println(currentDate);why is currentDate not updating when I update/change currentDay or currentMonth? I thought I could change integers as a program goes but currentDate will continue to print out 1 and 2 despite the in.nextInt. Any help would be appreciated.
Imagine the following piece of code
Template("Hello {name}, you are {position} in line").format(name="Alice", position=12, extra=42)
Would you rather that an error be thrown due to an unbound key (extra) being passed or should it be ignored?
I didn't find much languages even having such string templating built in except other than Python (string.format) and Rust (format!), in Python the extra key/value is ignored, while Rust will throw an exception.
What would be your approach?