Java generating Strings with placeholders

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

    This can be done in a single line without the use of library. Please check java.text.MessageFormat class.

    Example

    String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
    String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
    

    Output will be

    test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4
    

提交回复
热议问题