Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generating Strings with placeholders

Tags:

java

string

I'm looking for something to achieve the following:

String s = "hello {}!"; s = generate(s, new Object[]{ "world" }); assertEquals(s, "hello world!"); // should be true 

I could write it myself, but It seems to me that I saw a library once which did this, probably it was the slf4j logger, but i don't want to write log messages. I just want to generate strings.

Do you know about a library which does this?

like image 451
ndrizza Avatar asked Jun 28 '13 12:06

ndrizza


People also ask

How do you add a placeholder to a string?

printf("%d %d", 42, 23); We've put two %d symbols in the template String. These two symbols represent placeholders for a certain type of value. For instance, the %d is a placeholder for a decimal numeric value.

What are placeholders in Java?

A Placeholder is a predefined location in a JSP that displays a single piece of web content at a time that is dynamically retrieved from the BEA Virtual Content Repository.


2 Answers

See String.format method.

String s = "hello %s!"; s = String.format(s, "world"); assertEquals(s, "hello world!"); // should be true 
like image 93
Grzegorz Żur Avatar answered Sep 21 '22 18:09

Grzegorz Żur


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); 
like image 32
Justinas Jakavonis Avatar answered Sep 19 '22 18:09

Justinas Jakavonis