为了在 Java 中替换字符串中的标记,我们使用 Message Format 类。Message Format 类提供了一种生成不依赖于语言的连接消息的方法。Message Format 类扩展了 Serializable 和 Cloneable 接口。
声明- java.text.MessageFormat 类声明如下 -
public class MessageFormat extends Format
该方法使用与参数编号和数组索引匹配的 params 数组中的对象来格式化消息并填充缺失的部分。MessageFormat.format(pattern, params)
format 方法有两个参数,一个模式和一个参数数组。该模式在 {} 花括号中包含占位符,它指示存储参数值的数组中的位置。
让我们看一个在 Java 中替换令牌的例子 -
import java.text.MessageFormat; public class Example { public static void main(String[] args) { Object[] obj = new Object[] { "Good", "!!"}; // Morning 参数有占位符 0 和 1,因此它介于 Good 和 !! //因此它替代!!带有早晨令牌的令牌 System.out.println(MessageFormat.format("{0} Morning {1}", obj)); } }输出结果
Good Morning !!