从未给出占位符参数的输出中删除空格

Remove whitespace from output where placeholder arguments not given

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

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

基本上,这个印刷品是什么:

My name is Peter (whitespace) Maxwell.

比方说,如果我的字符串有多个占位符并且我传递了一个空白 参数,在这种情况下,输出会为该空白参数添加空格。

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

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

场景 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 !!

您可以使用 正则表达式 将多个白色 space 字符替换为一个字符。喜欢,

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

也处理第二种情况

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

哪些输出(按要求)

My name is Peter Maxwell.

没有其他变化