Java generating Strings with placeholders

前端 未结 8 804
北恋
北恋 2020-12-15 14:46

I\'m looking for something to achieve the following:

String s = \"hello {}!\";
s = generate(s, new Object[]{ \"world\" });
assertEquals(s, \"hello world!\");         


        
相关标签:
8条回答
  • 2020-12-15 15:32

    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);
    
    0 讨论(0)
  • 2020-12-15 15:32

    If you can tolerate a different kind of placeholder (i.e. %s in place of {}) you can use String.format method for that:

    String s = "hello %s!";
    s = String.format(s, "world" );
    assertEquals(s, "hello world!"); // true
    
    0 讨论(0)
  • 2020-12-15 15:34

    See String.format method.

    String s = "hello %s!";
    s = String.format(s, "world");
    assertEquals(s, "hello world!"); // should be true
    
    0 讨论(0)
  • 2020-12-15 15:41

    You won't need a library; if you are using a recent version of Java, have a look at String.format:

    String.format("Hello %s!", "world");
    
    0 讨论(0)
  • 2020-12-15 15:42

    There are two solutions:

    • MessageFormat;
    • Formatter.

    Formatter is more recent even though it takes over printf() which is 40 years old...

    Your placeholder as you currently define it is one MessageFormat can use, but why use an antique technique? ;) Use Formatter.

    There is all the more reason to use Formatter that you don't need to escape single quotes! MessageFormat requires you to do so. Also, Formatter has a shortcut via String.format() to generate strings, and PrintWriters have .printf() (that includes System.out and System.err which are both PrintWriters by default)

    0 讨论(0)
  • 2020-12-15 15:44

    If you can change the format of your placeholder, you could use String.format(). If not, you could also replace it as pre-processing.

    String.format("hello %s!", "world");
    

    More information in this other thread.

    0 讨论(0)
提交回复
热议问题