Java generating Strings with placeholders

前端 未结 8 832
北恋
北恋 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: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)

提交回复
热议问题