javastringmessageformat

Remove whitespace from output where placeholder arguments not given


String str = "My name is {0} {1} {2}."

String st = MessageFormat.format(str, "Peter", "", "Maxwell");

So basically, what this print is :

My name is Peter (whitespace) Maxwell.

Let's say, If my string has got multiple placeholders and if I pass a blank argument, in that case the output adds up whitespace for that blank argument.

So, in our previous case, the output should be like:

My name is Peter Maxwell. (No extra whitespace between Peter and Maxwell)

Scenario 2:

String st = MessageFormat.format(str, "Peter", "Branson", "");

Actual:
**My name is Peter Branson (whitespace).**

Expected:
**My name is Peter Branson.**

What I want to achieve is, for every unsupplied placeholder argument the whitespace should not be part of the final output.

Would appreciate the response !!


Solution

  • You could use a regular expression to replace multiple white space characters with a single one. Like,

    String st = MessageFormat.format(str, "Peter", "", "Maxwell")
            .replaceAll("\\s+", " ");
    

    or to handle the second case as well

    String st = MessageFormat.format(str, "Peter", "", "Maxwell")
            .replaceAll("\\s+", " ")
            .replaceAll("\\s+\\.", ".");
    

    Which outputs (as requested)

    My name is Peter Maxwell.
    

    with no other changes