【问题标题】:Remove whitespace from output where placeholder arguments not given从未给出占位符参数的输出中删除空格
【发布时间】:2021-09-29 22:22:25
【问题描述】:
String str = "My name is {0} {1} {2}."

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

所以基本上,这个打印是什么:

我的名字是彼得(空白)麦克斯韦。

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

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

我的名字是 Peter Maxwell。(Peter 和 Maxwell 之间没有多余的空格)

场景 2:

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

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

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

我想要实现的是,对于每个未提供的占位符参数 空格不应成为最终输出的一部分。

不胜感激!!

【问题讨论】:

    标签: java string messageformat


    【解决方案1】:

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

    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.
    

    没有其他变化

    【讨论】:

    • 为什么我们在第二种情况下使用了两次 replaceAll()?能详细点吗?
    • @mindfreak 第一个replaceAll() 处理场景1。第二个处理场景2。您还可以根据三个输入字符串的长度使用不同的MessageFormat 字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2016-04-24
    • 2017-11-03
    • 1970-01-01
    • 2018-12-21
    相关资源
    最近更新 更多